blob: 4ba41b55cbbef56cf238702719d864ff64ddedf9 [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"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000025#include "clang/Basic/Diagnostic.h"
26#include "clang/Frontend/ASTUnit.h"
27#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000029#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000030#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000031#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000032#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000033#include "llvm/Support/Timer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000034#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000035#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000036
Benjamin Kramerc2a98162010-03-13 21:22:49 +000037// Needed to define L_TMPNAM on some systems.
38#include <cstdio>
39
Steve Naroff50398192009-08-28 15:28:48 +000040using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000041using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000042using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000043
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000044//===----------------------------------------------------------------------===//
45// Crash Reporting.
46//===----------------------------------------------------------------------===//
47
Ted Kremenekd7ffd082010-05-22 00:06:46 +000048#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000049#include "clang/Analysis/Support/SaveAndRestore.h"
50// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000051static const char *__crashreporter_info__ = 0;
52asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000053#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000054static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000055static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000056static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
57static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
58
59static unsigned SetCrashTracerInfo(const char *str,
60 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000061
Ted Kremenek254ba7c2010-01-07 23:13:53 +000062 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000063 while (crashtracer_strings[slot]) {
64 if (++slot == NUM_CRASH_STRINGS)
65 slot = 0;
66 }
67 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000068 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000069
70 // We need to create an aggregate string because multiple threads
71 // may be in this method at one time. The crash reporter string
72 // will attempt to overapproximate the set of in-flight invocations
73 // of this function. Race conditions can still cause this goal
74 // to not be achieved.
75 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000076 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000077 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
78 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
79 }
80 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
81 return slot;
82}
83
84static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000085 unsigned max_slot = 0;
86 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000087
Ted Kremenek254ba7c2010-01-07 23:13:53 +000088 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
89
90 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
91 if (agg_crashtracer_strings[i] &&
92 crashtracer_counter_id[i] > max_value) {
93 max_slot = i;
94 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000095 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000096
97 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000098}
99
100namespace {
101class ArgsCrashTracerInfo {
102 llvm::SmallString<1024> CrashString;
103 llvm::SmallString<1024> AggregateString;
104 unsigned crashtracerSlot;
105public:
106 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
107 : crashtracerSlot(0)
108 {
109 {
110 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000111 Out << "ClangCIndex [" << getClangFullVersion() << "]"
112 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000113 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
114 E=Args.end(); I!=E; ++I)
115 Out << ' ' << *I;
116 }
117 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
118 AggregateString);
119 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000120
Ted Kremenek29b72842010-01-07 22:49:05 +0000121 ~ArgsCrashTracerInfo() {
122 ResetCrashTracerInfo(crashtracerSlot);
123 }
124};
125}
126#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000127
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000128/// \brief The result of comparing two source ranges.
129enum RangeComparisonResult {
130 /// \brief Either the ranges overlap or one of the ranges is invalid.
131 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000132
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000133 /// \brief The first range ends before the second range starts.
134 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000135
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000136 /// \brief The first range starts after the second range ends.
137 RangeAfter
138};
139
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000140/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000141/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000142static RangeComparisonResult RangeCompare(SourceManager &SM,
143 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000144 SourceRange R2) {
145 assert(R1.isValid() && "First range is invalid?");
146 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000147 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000148 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000149 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000150 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000151 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000152 return RangeAfter;
153 return RangeOverlap;
154}
155
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000156/// \brief Determine if a source location falls within, before, or after a
157/// a given source range.
158static RangeComparisonResult LocationCompare(SourceManager &SM,
159 SourceLocation L, SourceRange R) {
160 assert(R.isValid() && "First range is invalid?");
161 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000162 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000163 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000164 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
165 return RangeBefore;
166 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
167 return RangeAfter;
168 return RangeOverlap;
169}
170
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000171/// \brief Translate a Clang source range into a CIndex source range.
172///
173/// Clang internally represents ranges where the end location points to the
174/// start of the token at the end. However, for external clients it is more
175/// useful to have a CXSourceRange be a proper half-open interval. This routine
176/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000177CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000178 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000179 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000180 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000181 // location accordingly.
182 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000183 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000184 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000185 unsigned Length = Lexer::MeasureTokenLength(EndLoc, 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
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000241 class SetParentRAII {
242 CXCursor &Parent;
243 Decl *&StmtParent;
244 CXCursor OldParent;
245
246 public:
247 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
248 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
249 {
250 Parent = NewParent;
251 if (clang_isDeclaration(Parent.kind))
252 StmtParent = getCursorDecl(Parent);
253 }
254
255 ~SetParentRAII() {
256 Parent = OldParent;
257 if (clang_isDeclaration(Parent.kind))
258 StmtParent = getCursorDecl(Parent);
259 }
260 };
261
Steve Naroff89922f82009-08-31 00:59:03 +0000262public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000263 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
264 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000265 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000266 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000267 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000268 {
269 Parent.kind = CXCursor_NoDeclFound;
270 Parent.data[0] = 0;
271 Parent.data[1] = 0;
272 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000273 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000274 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000275
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000276 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000277
278 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
279 getPreprocessedEntities();
280
Douglas Gregorb1373d02010-01-20 20:59:29 +0000281 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000282
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000283 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000284 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000285 bool VisitBlockDecl(BlockDecl *B);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000286 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000287 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
288 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000289 bool VisitTagDecl(TagDecl *D);
290 bool VisitEnumConstantDecl(EnumConstantDecl *D);
291 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
292 bool VisitFunctionDecl(FunctionDecl *ND);
293 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000294 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000295 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
296 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
297 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
298 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000299 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000300 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
301 bool VisitObjCImplDecl(ObjCImplDecl *D);
302 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
303 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
304 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
305 // etc.
306 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
307 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
308 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000309 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000310 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000311
312 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000313 // FIXME: QualifiedTypeLoc doesn't provide any location information
314 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000315 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000316 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
317 bool VisitTagTypeLoc(TagTypeLoc TL);
318 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
319 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000320 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000321 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
322 bool VisitPointerTypeLoc(PointerTypeLoc TL);
323 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
324 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
325 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
326 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
327 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
328 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000329 // FIXME: Implement for TemplateSpecializationTypeLoc
330 // FIXME: Implement visitors here when the unimplemented TypeLocs get
331 // implemented
332 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
333 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000334
Douglas Gregora59e3902010-01-21 23:27:09 +0000335 // Statement visitors
336 bool VisitStmt(Stmt *S);
337 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000338 // FIXME: LabelStmt label?
339 bool VisitIfStmt(IfStmt *S);
340 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000341 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000342 bool VisitWhileStmt(WhileStmt *S);
343 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000344// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000345
Douglas Gregor336fd812010-01-23 00:40:08 +0000346 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000347 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
348 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000349 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000350 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000351 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000352 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000353 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000354 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000355 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000356 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000357 // FIXME: AddrLabelExpr (once we have cursors for labels)
358 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
359 bool VisitVAArgExpr(VAArgExpr *E);
360 // FIXME: InitListExpr (for the designators)
361 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000362};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000363
Ted Kremenekab188932010-01-05 19:32:54 +0000364} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000365
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000366static SourceRange getRawCursorExtent(CXCursor C);
367
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000368RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000369 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
370}
371
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372/// \brief Visit the given cursor and, if requested by the visitor,
373/// its children.
374///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000375/// \param Cursor the cursor to visit.
376///
377/// \param CheckRegionOfInterest if true, then the caller already checked that
378/// this cursor is within the region of interest.
379///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000380/// \returns true if the visitation should be aborted, false if it
381/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000382bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000383 if (clang_isInvalid(Cursor.kind))
384 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000385
Douglas Gregorb1373d02010-01-20 20:59:29 +0000386 if (clang_isDeclaration(Cursor.kind)) {
387 Decl *D = getCursorDecl(Cursor);
388 assert(D && "Invalid declaration cursor");
389 if (D->getPCHLevel() > MaxPCHLevel)
390 return false;
391
392 if (D->isImplicit())
393 return false;
394 }
395
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000396 // If we have a range of interest, and this cursor doesn't intersect with it,
397 // we're done.
398 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000399 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000400 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000401 return false;
402 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000403
Douglas Gregorb1373d02010-01-20 20:59:29 +0000404 switch (Visitor(Cursor, Parent, ClientData)) {
405 case CXChildVisit_Break:
406 return true;
407
408 case CXChildVisit_Continue:
409 return false;
410
411 case CXChildVisit_Recurse:
412 return VisitChildren(Cursor);
413 }
414
Douglas Gregorfd643772010-01-25 16:45:46 +0000415 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000416}
417
Douglas Gregor788f5a12010-03-20 00:41:21 +0000418std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
419CursorVisitor::getPreprocessedEntities() {
420 PreprocessingRecord &PPRec
421 = *TU->getPreprocessor().getPreprocessingRecord();
422
423 bool OnlyLocalDecls
424 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
425
426 // There is no region of interest; we have to walk everything.
427 if (RegionOfInterest.isInvalid())
428 return std::make_pair(PPRec.begin(OnlyLocalDecls),
429 PPRec.end(OnlyLocalDecls));
430
431 // Find the file in which the region of interest lands.
432 SourceManager &SM = TU->getSourceManager();
433 std::pair<FileID, unsigned> Begin
434 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
435 std::pair<FileID, unsigned> End
436 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
437
438 // The region of interest spans files; we have to walk everything.
439 if (Begin.first != End.first)
440 return std::make_pair(PPRec.begin(OnlyLocalDecls),
441 PPRec.end(OnlyLocalDecls));
442
443 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
444 = TU->getPreprocessedEntitiesByFile();
445 if (ByFileMap.empty()) {
446 // Build the mapping from files to sets of preprocessed entities.
447 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
448 EEnd = PPRec.end(OnlyLocalDecls);
449 E != EEnd; ++E) {
450 std::pair<FileID, unsigned> P
451 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
452 ByFileMap[P.first].push_back(*E);
453 }
454 }
455
456 return std::make_pair(ByFileMap[Begin.first].begin(),
457 ByFileMap[Begin.first].end());
458}
459
Douglas Gregorb1373d02010-01-20 20:59:29 +0000460/// \brief Visit the children of the given cursor.
461///
462/// \returns true if the visitation should be aborted, false if it
463/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000464bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000465 if (clang_isReference(Cursor.kind)) {
466 // By definition, references have no children.
467 return false;
468 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000469
470 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000471 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000472 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000473
Douglas Gregorb1373d02010-01-20 20:59:29 +0000474 if (clang_isDeclaration(Cursor.kind)) {
475 Decl *D = getCursorDecl(Cursor);
476 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000477 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000478 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000479
Douglas Gregora59e3902010-01-21 23:27:09 +0000480 if (clang_isStatement(Cursor.kind))
481 return Visit(getCursorStmt(Cursor));
482 if (clang_isExpression(Cursor.kind))
483 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000484
Douglas Gregorb1373d02010-01-20 20:59:29 +0000485 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000486 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000487 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
488 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000489 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
490 TLEnd = CXXUnit->top_level_end();
491 TL != TLEnd; ++TL) {
492 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000493 return true;
494 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000495 } else if (VisitDeclContext(
496 CXXUnit->getASTContext().getTranslationUnitDecl()))
497 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000498
Douglas Gregor0396f462010-03-19 05:22:59 +0000499 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000500 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 // FIXME: Once we have the ability to deserialize a preprocessing record,
502 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000503 PreprocessingRecord::iterator E, EEnd;
504 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000505 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
506 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
507 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000508
Douglas Gregor0396f462010-03-19 05:22:59 +0000509 continue;
510 }
511
512 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
513 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
514 return true;
515
516 continue;
517 }
518 }
519 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000520 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000521 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000522
Douglas Gregorb1373d02010-01-20 20:59:29 +0000523 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 return false;
525}
526
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000527bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000528 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
529 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000530
Ted Kremenek664cffd2010-07-22 11:30:19 +0000531 if (Stmt *Body = B->getBody())
532 return Visit(MakeCXCursor(Body, StmtParent, TU));
533
534 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000535}
536
Douglas Gregorb1373d02010-01-20 20:59:29 +0000537bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000538 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000539 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000540
Ted Kremenek23173d72010-05-18 21:09:07 +0000541 Decl *D = *I;
542 if (D->getLexicalDeclContext() != DC)
543 continue;
544
545 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000546
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000547 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000548 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000549 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000550 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000551
552 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000553 case RangeBefore:
554 // This declaration comes before the region of interest; skip it.
555 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000556
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000557 case RangeAfter:
558 // This declaration comes after the region of interest; we're done.
559 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000560
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000561 case RangeOverlap:
562 // This declaration overlaps the region of interest; visit it.
563 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000564 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000565 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000566
Daniel Dunbard52864b2010-02-14 10:02:57 +0000567 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000568 return true;
569 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000570
Douglas Gregorb1373d02010-01-20 20:59:29 +0000571 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000572}
573
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000574bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
575 llvm_unreachable("Translation units are visited directly by Visit()");
576 return false;
577}
578
579bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
580 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
581 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000582
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000583 return false;
584}
585
586bool CursorVisitor::VisitTagDecl(TagDecl *D) {
587 return VisitDeclContext(D);
588}
589
590bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
591 if (Expr *Init = D->getInitExpr())
592 return Visit(MakeCXCursor(Init, StmtParent, TU));
593 return false;
594}
595
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000596bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
597 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
598 if (Visit(TSInfo->getTypeLoc()))
599 return true;
600
601 return false;
602}
603
Douglas Gregorb1373d02010-01-20 20:59:29 +0000604bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000605 if (VisitDeclaratorDecl(ND))
606 return true;
607
Douglas Gregora59e3902010-01-21 23:27:09 +0000608 if (ND->isThisDeclarationADefinition() &&
609 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
610 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000611
Douglas Gregorb1373d02010-01-20 20:59:29 +0000612 return false;
613}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000614
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000615bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
616 if (VisitDeclaratorDecl(D))
617 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000618
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000619 if (Expr *BitWidth = D->getBitWidth())
620 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000621
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000622 return false;
623}
624
625bool CursorVisitor::VisitVarDecl(VarDecl *D) {
626 if (VisitDeclaratorDecl(D))
627 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000628
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000629 if (Expr *Init = D->getInit())
630 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000631
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000632 return false;
633}
634
635bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000636 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
637 if (Visit(TSInfo->getTypeLoc()))
638 return true;
639
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000640 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000641 PEnd = ND->param_end();
642 P != PEnd; ++P) {
643 if (Visit(MakeCXCursor(*P, TU)))
644 return true;
645 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000646
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000647 if (ND->isThisDeclarationADefinition() &&
648 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
649 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000650
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000651 return false;
652}
653
Douglas Gregora59e3902010-01-21 23:27:09 +0000654bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
655 return VisitDeclContext(D);
656}
657
Douglas Gregorb1373d02010-01-20 20:59:29 +0000658bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000659 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
660 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000661 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000662
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000663 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
664 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
665 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000666 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000667 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000668
Douglas Gregora59e3902010-01-21 23:27:09 +0000669 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000670}
671
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000672bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
673 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
674 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
675 E = PID->protocol_end(); I != E; ++I, ++PL)
676 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
677 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000678
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000679 return VisitObjCContainerDecl(PID);
680}
681
Ted Kremenek23173d72010-05-18 21:09:07 +0000682bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000683 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
684 return true;
685
Ted Kremenek23173d72010-05-18 21:09:07 +0000686 // FIXME: This implements a workaround with @property declarations also being
687 // installed in the DeclContext for the @interface. Eventually this code
688 // should be removed.
689 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
690 if (!CDecl || !CDecl->IsClassExtension())
691 return false;
692
693 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
694 if (!ID)
695 return false;
696
697 IdentifierInfo *PropertyId = PD->getIdentifier();
698 ObjCPropertyDecl *prevDecl =
699 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
700
701 if (!prevDecl)
702 return false;
703
704 // Visit synthesized methods since they will be skipped when visiting
705 // the @interface.
706 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
707 if (MD->isSynthesized())
708 if (Visit(MakeCXCursor(MD, TU)))
709 return true;
710
711 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
712 if (MD->isSynthesized())
713 if (Visit(MakeCXCursor(MD, TU)))
714 return true;
715
716 return false;
717}
718
Douglas Gregorb1373d02010-01-20 20:59:29 +0000719bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000720 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000721 if (D->getSuperClass() &&
722 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000723 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000724 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000725 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000726
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000727 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
728 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
729 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000730 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000731 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000732
Douglas Gregora59e3902010-01-21 23:27:09 +0000733 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000734}
735
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000736bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
737 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000738}
739
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000740bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000741 // 'ID' could be null when dealing with invalid code.
742 if (ObjCInterfaceDecl *ID = D->getClassInterface())
743 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
744 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000745
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000746 return VisitObjCImplDecl(D);
747}
748
749bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
750#if 0
751 // Issue callbacks for super class.
752 // FIXME: No source location information!
753 if (D->getSuperClass() &&
754 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000755 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000756 TU)))
757 return true;
758#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000759
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000760 return VisitObjCImplDecl(D);
761}
762
763bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
764 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
765 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
766 E = D->protocol_end();
767 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000768 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000769 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000770
771 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000772}
773
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000774bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
775 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
776 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
777 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000778
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000779 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000780}
781
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000782bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
783 return VisitDeclContext(D);
784}
785
Ted Kremeneka0536d82010-05-07 01:04:29 +0000786bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
787 return VisitDeclContext(D);
788}
789
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000790bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
791 ASTContext &Context = TU->getASTContext();
792
793 // Some builtin types (such as Objective-C's "id", "sel", and
794 // "Class") have associated declarations. Create cursors for those.
795 QualType VisitType;
796 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000797 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000798 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000799 case BuiltinType::Char_U:
800 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000801 case BuiltinType::Char16:
802 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000803 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000804 case BuiltinType::UInt:
805 case BuiltinType::ULong:
806 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000807 case BuiltinType::UInt128:
808 case BuiltinType::Char_S:
809 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000810 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000811 case BuiltinType::Short:
812 case BuiltinType::Int:
813 case BuiltinType::Long:
814 case BuiltinType::LongLong:
815 case BuiltinType::Int128:
816 case BuiltinType::Float:
817 case BuiltinType::Double:
818 case BuiltinType::LongDouble:
819 case BuiltinType::NullPtr:
820 case BuiltinType::Overload:
821 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000822 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000823
824 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000825 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000826
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000827 case BuiltinType::ObjCId:
828 VisitType = Context.getObjCIdType();
829 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000830
831 case BuiltinType::ObjCClass:
832 VisitType = Context.getObjCClassType();
833 break;
834
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000835 case BuiltinType::ObjCSel:
836 VisitType = Context.getObjCSelType();
837 break;
838 }
839
840 if (!VisitType.isNull()) {
841 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000843 TU));
844 }
845
846 return false;
847}
848
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000849bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
850 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
851}
852
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000853bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
854 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
855}
856
857bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
858 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
859}
860
861bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
862 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
863 return true;
864
John McCallc12c5bb2010-05-15 11:32:37 +0000865 return false;
866}
867
868bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
869 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
870 return true;
871
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000872 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
873 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
874 TU)))
875 return true;
876 }
877
878 return false;
879}
880
881bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +0000882 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000883}
884
885bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
886 return Visit(TL.getPointeeLoc());
887}
888
889bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
890 return Visit(TL.getPointeeLoc());
891}
892
893bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
894 return Visit(TL.getPointeeLoc());
895}
896
897bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000898 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000899}
900
901bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000902 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000903}
904
905bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
906 if (Visit(TL.getResultLoc()))
907 return true;
908
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000909 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000910 if (Decl *D = TL.getArg(I))
911 if (Visit(MakeCXCursor(D, TU)))
912 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000913
914 return false;
915}
916
917bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
918 if (Visit(TL.getElementLoc()))
919 return true;
920
921 if (Expr *Size = TL.getSizeExpr())
922 return Visit(MakeCXCursor(Size, StmtParent, TU));
923
924 return false;
925}
926
Douglas Gregor2332c112010-01-21 20:48:56 +0000927bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
928 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
929}
930
931bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
932 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
933 return Visit(TSInfo->getTypeLoc());
934
935 return false;
936}
937
Douglas Gregora59e3902010-01-21 23:27:09 +0000938bool CursorVisitor::VisitStmt(Stmt *S) {
939 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
940 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000941 if (Stmt *C = *Child)
942 if (Visit(MakeCXCursor(C, StmtParent, TU)))
943 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +0000944 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000945
Douglas Gregora59e3902010-01-21 23:27:09 +0000946 return false;
947}
948
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000949bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
950 // Specially handle CaseStmts because they can be nested, e.g.:
951 //
952 // case 1:
953 // case 2:
954 //
955 // In this case the second CaseStmt is the child of the first. Walking
956 // these recursively can blow out the stack.
957 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
958 while (true) {
959 // Set the Parent field to Cursor, then back to its old value once we're
960 // done.
961 SetParentRAII SetParent(Parent, StmtParent, Cursor);
962
963 if (Stmt *LHS = S->getLHS())
964 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
965 return true;
966 if (Stmt *RHS = S->getRHS())
967 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
968 return true;
969 if (Stmt *SubStmt = S->getSubStmt()) {
970 if (!isa<CaseStmt>(SubStmt))
971 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
972
973 // Specially handle 'CaseStmt' so that we don't blow out the stack.
974 CaseStmt *CS = cast<CaseStmt>(SubStmt);
975 Cursor = MakeCXCursor(CS, StmtParent, TU);
976 if (RegionOfInterest.isValid()) {
977 SourceRange Range = CS->getSourceRange();
978 if (Range.isInvalid() || CompareRegionOfInterest(Range))
979 return false;
980 }
981
982 switch (Visitor(Cursor, Parent, ClientData)) {
983 case CXChildVisit_Break: return true;
984 case CXChildVisit_Continue: return false;
985 case CXChildVisit_Recurse:
986 // Perform tail-recursion manually.
987 S = CS;
988 continue;
989 }
990 }
991 return false;
992 }
993}
994
Douglas Gregora59e3902010-01-21 23:27:09 +0000995bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
996 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
997 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000998 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000999 return true;
1000 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001001
Douglas Gregora59e3902010-01-21 23:27:09 +00001002 return false;
1003}
1004
Douglas Gregorf5bab412010-01-22 01:00:11 +00001005bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1006 if (VarDecl *Var = S->getConditionVariable()) {
1007 if (Visit(MakeCXCursor(Var, TU)))
1008 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001009 }
1010
Douglas Gregor263b47b2010-01-25 16:12:32 +00001011 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1012 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001013 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1014 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001015 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1016 return true;
1017
1018 return false;
1019}
1020
1021bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1022 if (VarDecl *Var = S->getConditionVariable()) {
1023 if (Visit(MakeCXCursor(Var, TU)))
1024 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001025 }
1026
Douglas Gregor263b47b2010-01-25 16:12:32 +00001027 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1028 return true;
1029 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1030 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001031
Douglas Gregor263b47b2010-01-25 16:12:32 +00001032 return false;
1033}
1034
1035bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1036 if (VarDecl *Var = S->getConditionVariable()) {
1037 if (Visit(MakeCXCursor(Var, TU)))
1038 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001039 }
1040
Douglas Gregor263b47b2010-01-25 16:12:32 +00001041 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1042 return true;
1043 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001044 return true;
1045
Douglas Gregor263b47b2010-01-25 16:12:32 +00001046 return false;
1047}
1048
1049bool CursorVisitor::VisitForStmt(ForStmt *S) {
1050 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1051 return true;
1052 if (VarDecl *Var = S->getConditionVariable()) {
1053 if (Visit(MakeCXCursor(Var, TU)))
1054 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001055 }
1056
Douglas Gregor263b47b2010-01-25 16:12:32 +00001057 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1058 return true;
1059 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1060 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001061 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1062 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001063
Douglas Gregorf5bab412010-01-22 01:00:11 +00001064 return false;
1065}
1066
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001067bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1068 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1069 return true;
1070
1071 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1072 return true;
1073
1074 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1075 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1076 return true;
1077
1078 return false;
1079}
1080
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001081bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1082 return Visit(B->getBlockDecl());
1083}
1084
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001085bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1086 // FIXME: Visit fields as well?
1087 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1088 return true;
1089
1090 return VisitExpr(E);
1091}
1092
Douglas Gregor336fd812010-01-23 00:40:08 +00001093bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1094 if (E->isArgumentType()) {
1095 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1096 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001097
Douglas Gregor336fd812010-01-23 00:40:08 +00001098 return false;
1099 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001100
Douglas Gregor336fd812010-01-23 00:40:08 +00001101 return VisitExpr(E);
1102}
1103
1104bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1105 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1106 if (Visit(TSInfo->getTypeLoc()))
1107 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001108
Douglas Gregor336fd812010-01-23 00:40:08 +00001109 return VisitCastExpr(E);
1110}
1111
1112bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1113 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1114 if (Visit(TSInfo->getTypeLoc()))
1115 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001116
Douglas Gregor336fd812010-01-23 00:40:08 +00001117 return VisitExpr(E);
1118}
1119
Douglas Gregor648220e2010-08-10 15:02:34 +00001120bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1121 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1122 Visit(E->getArgTInfo2()->getTypeLoc());
1123}
1124
1125bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1126 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1127 return true;
1128
1129 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1130}
1131
Douglas Gregorc2350e52010-03-08 16:40:19 +00001132bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001133 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1134 if (Visit(TSInfo->getTypeLoc()))
1135 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001136
1137 return VisitExpr(E);
1138}
1139
Douglas Gregor81d34662010-04-20 15:39:42 +00001140bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1141 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1142}
1143
1144
Ted Kremenek09dfa372010-02-18 05:46:33 +00001145bool CursorVisitor::VisitAttributes(Decl *D) {
1146 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1147 if (Visit(MakeCXCursor(A, D, TU)))
1148 return true;
1149
1150 return false;
1151}
1152
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001153extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001154CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1155 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +00001156 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001157 if (excludeDeclarationsFromPCH)
1158 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001159 if (displayDiagnostics)
1160 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001161 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001162}
1163
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001164void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001165 if (CIdx)
1166 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001167 if (getenv("LIBCLANG_TIMING"))
1168 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001169}
1170
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001171void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001172 if (CIdx) {
1173 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1174 CXXIdx->setUseExternalASTGeneration(value);
1175 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001176}
1177
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001178CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001179 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001180 if (!CIdx)
1181 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001182
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001183 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001184
Douglas Gregor28019772010-04-05 23:52:57 +00001185 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1186 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001187 CXXIdx->getOnlyLocalDecls(),
1188 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001189}
1190
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001191unsigned clang_defaultEditingTranslationUnitOptions() {
1192 return CXTranslationUnit_PrecompiledPreamble;
1193}
1194
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001195CXTranslationUnit
1196clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1197 const char *source_filename,
1198 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001199 const char **command_line_args,
1200 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001201 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001202 return clang_parseTranslationUnit(CIdx, source_filename,
1203 command_line_args, num_command_line_args,
1204 unsaved_files, num_unsaved_files,
1205 CXTranslationUnit_DetailedPreprocessingRecord);
1206}
1207
1208CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1209 const char *source_filename,
1210 const char **command_line_args,
1211 int num_command_line_args,
1212 struct CXUnsavedFile *unsaved_files,
1213 unsigned num_unsaved_files,
1214 unsigned options) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001215 if (!CIdx)
1216 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001217
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001218 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1219
Douglas Gregor44c181a2010-07-23 00:33:23 +00001220 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001221 bool CompleteTranslationUnit
1222 = ((options & CXTranslationUnit_Incomplete) == 0);
1223
Douglas Gregor5352ac02010-01-28 00:27:43 +00001224 // Configure the diagnostics.
1225 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001226 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1227 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001228
Douglas Gregor4db64a42010-01-23 00:14:00 +00001229 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1230 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001231 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001232 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001233 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001234 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1235 Buffer));
1236 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001237
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001238 if (!CXXIdx->getUseExternalASTGeneration()) {
1239 llvm::SmallVector<const char *, 16> Args;
1240
1241 // The 'source_filename' argument is optional. If the caller does not
1242 // specify it then it is assumed that the source file is specified
1243 // in the actual argument list.
1244 if (source_filename)
1245 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001246
1247 // Since the Clang C library is primarily used by batch tools dealing with
1248 // (often very broken) source code, where spell-checking can have a
1249 // significant negative impact on performance (particularly when
1250 // precompiled headers are involved), we disable it by default.
1251 // Note that we place this argument early in the list, so that it can be
1252 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001253 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001254
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001255 Args.insert(Args.end(), command_line_args,
1256 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001257
Douglas Gregor44c181a2010-07-23 00:33:23 +00001258 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001259 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1260 Args.push_back("-Xclang");
1261 Args.push_back("-detailed-preprocessing-record");
1262 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001263
Douglas Gregor5352ac02010-01-28 00:27:43 +00001264 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001265
Ted Kremenek29b72842010-01-07 22:49:05 +00001266#ifdef USE_CRASHTRACER
1267 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001268#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001269
Daniel Dunbar94220972009-12-05 02:17:18 +00001270 llvm::OwningPtr<ASTUnit> Unit(
1271 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001272 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001273 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001274 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001275 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001276 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001277 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001278 PrecompilePreamble,
1279 CompleteTranslationUnit));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001280
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001281 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001282 // Make sure to check that 'Unit' is non-NULL.
1283 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001284 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1285 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001286 D != DEnd; ++D) {
1287 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001288 CXString Msg = clang_formatDiagnostic(&Diag,
1289 clang_defaultDiagnosticDisplayOptions());
1290 fprintf(stderr, "%s\n", clang_getCString(Msg));
1291 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001292 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001293#ifdef LLVM_ON_WIN32
1294 // On Windows, force a flush, since there may be multiple copies of
1295 // stderr and stdout in the file system, all with different buffers
1296 // but writing to the same device.
1297 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001298#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001299 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001300 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001301
1302 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001303 }
1304
Ted Kremenek139ba862009-10-22 00:03:57 +00001305 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001306 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001307
Ted Kremenek139ba862009-10-22 00:03:57 +00001308 // First add the complete path to the 'clang' executable.
1309 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001310 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001311
Ted Kremenek139ba862009-10-22 00:03:57 +00001312 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001313 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001314
Ted Kremenek139ba862009-10-22 00:03:57 +00001315 // The 'source_filename' argument is optional. If the caller does not
1316 // specify it then it is assumed that the source file is specified
1317 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001318 if (source_filename)
1319 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001320
Steve Naroff37b5ac22009-10-15 20:50:09 +00001321 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001322 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001323 char astTmpFile[L_tmpnam];
1324 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001325
1326 // Since the Clang C library is primarily used by batch tools dealing with
1327 // (often very broken) source code, where spell-checking can have a
1328 // significant negative impact on performance (particularly when
1329 // precompiled headers are involved), we disable it by default.
1330 // Note that we place this argument early in the list, so that it can be
1331 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001332 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001333
Douglas Gregor4db64a42010-01-23 00:14:00 +00001334 // Remap any unsaved files to temporary files.
1335 std::vector<llvm::sys::Path> TemporaryFiles;
1336 std::vector<std::string> RemapArgs;
1337 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1338 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001339
Douglas Gregor4db64a42010-01-23 00:14:00 +00001340 // The pointers into the elements of RemapArgs are stable because we
1341 // won't be adding anything to RemapArgs after this point.
1342 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1343 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001344
Ted Kremenek139ba862009-10-22 00:03:57 +00001345 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1346 for (int i = 0; i < num_command_line_args; ++i)
1347 if (const char *arg = command_line_args[i]) {
1348 if (strcmp(arg, "-o") == 0) {
1349 ++i; // Also skip the matching argument.
1350 continue;
1351 }
1352 if (strcmp(arg, "-emit-ast") == 0 ||
1353 strcmp(arg, "-c") == 0 ||
1354 strcmp(arg, "-fsyntax-only") == 0) {
1355 continue;
1356 }
1357
1358 // Keep the argument.
1359 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001360 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001361
Douglas Gregord93256e2010-01-28 06:00:51 +00001362 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001363 char tmpFileResults[L_tmpnam];
1364 char *tmpResultsFileName = tmpnam(tmpFileResults);
1365 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001366 TemporaryFiles.push_back(DiagnosticsFile);
1367 argv.push_back("-fdiagnostics-binary");
1368
Douglas Gregor44c181a2010-07-23 00:33:23 +00001369 // Do we need the detailed preprocessing record?
1370 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1371 argv.push_back("-Xclang");
1372 argv.push_back("-detailed-preprocessing-record");
1373 }
1374
Ted Kremenek139ba862009-10-22 00:03:57 +00001375 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001376 argv.push_back(NULL);
1377
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001378 // Invoke 'clang'.
1379 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1380 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001381 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001382 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1383 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001384 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001385 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001386 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001387
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001388 if (!ErrMsg.empty()) {
1389 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001390 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001391 I != E; ++I) {
1392 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001393 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001394 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001395 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001396
Daniel Dunbar32141c82010-02-23 20:23:45 +00001397 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001398 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001399
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001400 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001401 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001402 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001403 RemappedFiles.size(),
1404 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001405 if (ATU) {
1406 LoadSerializedDiagnostics(DiagnosticsFile,
1407 num_unsaved_files, unsaved_files,
1408 ATU->getFileManager(),
1409 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001410 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001411 } else if (CXXIdx->getDisplayDiagnostics()) {
1412 // We failed to load the ASTUnit, but we can still deserialize the
1413 // diagnostics and emit them.
1414 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001415 Diagnostic Diag;
1416 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001417 // FIXME: Faked LangOpts!
1418 LangOptions LangOpts;
1419 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1420 LoadSerializedDiagnostics(DiagnosticsFile,
1421 num_unsaved_files, unsaved_files,
1422 FileMgr, SourceMgr, Diags);
1423 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1424 DEnd = Diags.end();
1425 D != DEnd; ++D) {
1426 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001427 CXString Msg = clang_formatDiagnostic(&Diag,
1428 clang_defaultDiagnosticDisplayOptions());
1429 fprintf(stderr, "%s\n", clang_getCString(Msg));
1430 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001431 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001432
1433#ifdef LLVM_ON_WIN32
1434 // On Windows, force a flush, since there may be multiple copies of
1435 // stderr and stdout in the file system, all with different buffers
1436 // but writing to the same device.
1437 fflush(stderr);
1438#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001439 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001440
Douglas Gregor313e26c2010-02-18 23:35:40 +00001441 if (ATU) {
1442 // Make the translation unit responsible for destroying all temporary files.
1443 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1444 ATU->addTemporaryFile(TemporaryFiles[i]);
1445 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1446 } else {
1447 // Destroy all of the temporary files now; they can't be referenced any
1448 // longer.
1449 llvm::sys::Path(astTmpFile).eraseFromDisk();
1450 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1451 TemporaryFiles[i].eraseFromDisk();
1452 }
1453
Steve Naroffe19944c2009-10-15 22:23:48 +00001454 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001455}
1456
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001457int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName) {
1458 if (!TU)
1459 return 1;
1460
1461 return static_cast<ASTUnit *>(TU)->Save(FileName);
1462}
1463
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001464void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001465 if (CTUnit)
1466 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001467}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001468
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001469unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1470 return CXReparse_None;
1471}
1472
Douglas Gregorabc563f2010-07-19 21:46:24 +00001473int clang_reparseTranslationUnit(CXTranslationUnit TU,
1474 unsigned num_unsaved_files,
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001475 struct CXUnsavedFile *unsaved_files,
1476 unsigned options) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001477 if (!TU)
1478 return 1;
1479
1480 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1481 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1482 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1483 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001484 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001485 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1486 Buffer));
1487 }
1488
1489 return static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1490 RemappedFiles.size())? 1 : 0;
1491}
Douglas Gregordf95a132010-08-09 20:45:32 +00001492
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001493CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001494 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001495 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001496
Steve Naroff77accc12009-09-03 18:19:54 +00001497 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001498 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001499}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001500
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001501CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001502 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001503 return Result;
1504}
1505
Ted Kremenekfb480492010-01-13 21:46:36 +00001506} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001507
Ted Kremenekfb480492010-01-13 21:46:36 +00001508//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001509// CXSourceLocation and CXSourceRange Operations.
1510//===----------------------------------------------------------------------===//
1511
Douglas Gregorb9790342010-01-22 21:44:22 +00001512extern "C" {
1513CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001514 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001515 return Result;
1516}
1517
1518unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001519 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1520 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1521 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001522}
1523
1524CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1525 CXFile file,
1526 unsigned line,
1527 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001528 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001529 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001530
Douglas Gregorb9790342010-01-22 21:44:22 +00001531 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1532 SourceLocation SLoc
1533 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001534 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001535 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001536
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001537 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001538}
1539
Douglas Gregor5352ac02010-01-28 00:27:43 +00001540CXSourceRange clang_getNullRange() {
1541 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1542 return Result;
1543}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001544
Douglas Gregor5352ac02010-01-28 00:27:43 +00001545CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1546 if (begin.ptr_data[0] != end.ptr_data[0] ||
1547 begin.ptr_data[1] != end.ptr_data[1])
1548 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001549
1550 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001551 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001552 return Result;
1553}
1554
Douglas Gregor46766dc2010-01-26 19:19:08 +00001555void clang_getInstantiationLocation(CXSourceLocation location,
1556 CXFile *file,
1557 unsigned *line,
1558 unsigned *column,
1559 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001560 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1561
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001562 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001563 if (file)
1564 *file = 0;
1565 if (line)
1566 *line = 0;
1567 if (column)
1568 *column = 0;
1569 if (offset)
1570 *offset = 0;
1571 return;
1572 }
1573
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001574 const SourceManager &SM =
1575 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001576 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001577
1578 if (file)
1579 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1580 if (line)
1581 *line = SM.getInstantiationLineNumber(InstLoc);
1582 if (column)
1583 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001584 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001585 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001586}
1587
Douglas Gregor1db19de2010-01-19 21:36:55 +00001588CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001589 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001590 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001591 return Result;
1592}
1593
1594CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001595 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001596 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001597 return Result;
1598}
1599
Douglas Gregorb9790342010-01-22 21:44:22 +00001600} // end: extern "C"
1601
Douglas Gregor1db19de2010-01-19 21:36:55 +00001602//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001603// CXFile Operations.
1604//===----------------------------------------------------------------------===//
1605
1606extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001607CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001608 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001609 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001610
Steve Naroff88145032009-10-27 14:35:18 +00001611 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001612 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001613}
1614
1615time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001616 if (!SFile)
1617 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001618
Steve Naroff88145032009-10-27 14:35:18 +00001619 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1620 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001621}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001622
Douglas Gregorb9790342010-01-22 21:44:22 +00001623CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1624 if (!tu)
1625 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001626
Douglas Gregorb9790342010-01-22 21:44:22 +00001627 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001628
Douglas Gregorb9790342010-01-22 21:44:22 +00001629 FileManager &FMgr = CXXUnit->getFileManager();
1630 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1631 return const_cast<FileEntry *>(File);
1632}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001633
Ted Kremenekfb480492010-01-13 21:46:36 +00001634} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001635
Ted Kremenekfb480492010-01-13 21:46:36 +00001636//===----------------------------------------------------------------------===//
1637// CXCursor Operations.
1638//===----------------------------------------------------------------------===//
1639
Ted Kremenekfb480492010-01-13 21:46:36 +00001640static Decl *getDeclFromExpr(Stmt *E) {
1641 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1642 return RefExpr->getDecl();
1643 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1644 return ME->getMemberDecl();
1645 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1646 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001647
Ted Kremenekfb480492010-01-13 21:46:36 +00001648 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1649 return getDeclFromExpr(CE->getCallee());
1650 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1651 return getDeclFromExpr(CE->getSubExpr());
1652 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1653 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001654
Ted Kremenekfb480492010-01-13 21:46:36 +00001655 return 0;
1656}
1657
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001658static SourceLocation getLocationFromExpr(Expr *E) {
1659 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1660 return /*FIXME:*/Msg->getLeftLoc();
1661 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1662 return DRE->getLocation();
1663 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1664 return Member->getMemberLoc();
1665 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1666 return Ivar->getLocation();
1667 return E->getLocStart();
1668}
1669
Ted Kremenekfb480492010-01-13 21:46:36 +00001670extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001671
1672unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001673 CXCursorVisitor visitor,
1674 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001675 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001676
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001677 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1678 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00001679 return CursorVis.VisitChildren(parent);
1680}
1681
Douglas Gregor78205d42010-01-20 21:45:58 +00001682static CXString getDeclSpelling(Decl *D) {
1683 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1684 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001685 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001686
Douglas Gregor78205d42010-01-20 21:45:58 +00001687 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001688 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001689
Douglas Gregor78205d42010-01-20 21:45:58 +00001690 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1691 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1692 // and returns different names. NamedDecl returns the class name and
1693 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001694 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001695
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001696 llvm::SmallString<1024> S;
1697 llvm::raw_svector_ostream os(S);
1698 ND->printName(os);
1699
1700 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001701}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001702
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001703CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001704 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001705 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001706
Steve Narofff334b4e2009-09-02 18:26:48 +00001707 if (clang_isReference(C.kind)) {
1708 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001709 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001710 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001711 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001712 }
1713 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001714 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001715 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001716 }
1717 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001718 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001719 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001720 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001721 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001722 case CXCursor_TypeRef: {
1723 TypeDecl *Type = getCursorTypeRef(C).first;
1724 assert(Type && "Missing type decl");
1725
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001726 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1727 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001728 }
1729
Daniel Dunbaracca7252009-11-30 20:42:49 +00001730 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001731 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001732 }
1733 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001734
1735 if (clang_isExpression(C.kind)) {
1736 Decl *D = getDeclFromExpr(getCursorExpr(C));
1737 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001738 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001739 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001740 }
1741
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001742 if (C.kind == CXCursor_MacroInstantiation)
1743 return createCXString(getCursorMacroInstantiation(C)->getName()
1744 ->getNameStart());
1745
Douglas Gregor572feb22010-03-18 18:04:21 +00001746 if (C.kind == CXCursor_MacroDefinition)
1747 return createCXString(getCursorMacroDefinition(C)->getName()
1748 ->getNameStart());
1749
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001750 if (clang_isDeclaration(C.kind))
1751 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001752
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001753 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001754}
1755
Ted Kremeneke68fff62010-02-17 00:41:32 +00001756CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001757 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001758 case CXCursor_FunctionDecl:
1759 return createCXString("FunctionDecl");
1760 case CXCursor_TypedefDecl:
1761 return createCXString("TypedefDecl");
1762 case CXCursor_EnumDecl:
1763 return createCXString("EnumDecl");
1764 case CXCursor_EnumConstantDecl:
1765 return createCXString("EnumConstantDecl");
1766 case CXCursor_StructDecl:
1767 return createCXString("StructDecl");
1768 case CXCursor_UnionDecl:
1769 return createCXString("UnionDecl");
1770 case CXCursor_ClassDecl:
1771 return createCXString("ClassDecl");
1772 case CXCursor_FieldDecl:
1773 return createCXString("FieldDecl");
1774 case CXCursor_VarDecl:
1775 return createCXString("VarDecl");
1776 case CXCursor_ParmDecl:
1777 return createCXString("ParmDecl");
1778 case CXCursor_ObjCInterfaceDecl:
1779 return createCXString("ObjCInterfaceDecl");
1780 case CXCursor_ObjCCategoryDecl:
1781 return createCXString("ObjCCategoryDecl");
1782 case CXCursor_ObjCProtocolDecl:
1783 return createCXString("ObjCProtocolDecl");
1784 case CXCursor_ObjCPropertyDecl:
1785 return createCXString("ObjCPropertyDecl");
1786 case CXCursor_ObjCIvarDecl:
1787 return createCXString("ObjCIvarDecl");
1788 case CXCursor_ObjCInstanceMethodDecl:
1789 return createCXString("ObjCInstanceMethodDecl");
1790 case CXCursor_ObjCClassMethodDecl:
1791 return createCXString("ObjCClassMethodDecl");
1792 case CXCursor_ObjCImplementationDecl:
1793 return createCXString("ObjCImplementationDecl");
1794 case CXCursor_ObjCCategoryImplDecl:
1795 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001796 case CXCursor_CXXMethod:
1797 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001798 case CXCursor_UnexposedDecl:
1799 return createCXString("UnexposedDecl");
1800 case CXCursor_ObjCSuperClassRef:
1801 return createCXString("ObjCSuperClassRef");
1802 case CXCursor_ObjCProtocolRef:
1803 return createCXString("ObjCProtocolRef");
1804 case CXCursor_ObjCClassRef:
1805 return createCXString("ObjCClassRef");
1806 case CXCursor_TypeRef:
1807 return createCXString("TypeRef");
1808 case CXCursor_UnexposedExpr:
1809 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001810 case CXCursor_BlockExpr:
1811 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001812 case CXCursor_DeclRefExpr:
1813 return createCXString("DeclRefExpr");
1814 case CXCursor_MemberRefExpr:
1815 return createCXString("MemberRefExpr");
1816 case CXCursor_CallExpr:
1817 return createCXString("CallExpr");
1818 case CXCursor_ObjCMessageExpr:
1819 return createCXString("ObjCMessageExpr");
1820 case CXCursor_UnexposedStmt:
1821 return createCXString("UnexposedStmt");
1822 case CXCursor_InvalidFile:
1823 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001824 case CXCursor_InvalidCode:
1825 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001826 case CXCursor_NoDeclFound:
1827 return createCXString("NoDeclFound");
1828 case CXCursor_NotImplemented:
1829 return createCXString("NotImplemented");
1830 case CXCursor_TranslationUnit:
1831 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001832 case CXCursor_UnexposedAttr:
1833 return createCXString("UnexposedAttr");
1834 case CXCursor_IBActionAttr:
1835 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001836 case CXCursor_IBOutletAttr:
1837 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00001838 case CXCursor_IBOutletCollectionAttr:
1839 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001840 case CXCursor_PreprocessingDirective:
1841 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001842 case CXCursor_MacroDefinition:
1843 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001844 case CXCursor_MacroInstantiation:
1845 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001846 case CXCursor_Namespace:
1847 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001848 case CXCursor_LinkageSpec:
1849 return createCXString("LinkageSpec");
Steve Naroff89922f82009-08-31 00:59:03 +00001850 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001851
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001852 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001853 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001854}
Steve Naroff89922f82009-08-31 00:59:03 +00001855
Ted Kremeneke68fff62010-02-17 00:41:32 +00001856enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1857 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001858 CXClientData client_data) {
1859 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1860 *BestCursor = cursor;
1861 return CXChildVisit_Recurse;
1862}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001863
Douglas Gregorb9790342010-01-22 21:44:22 +00001864CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1865 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001866 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001867
Douglas Gregorb9790342010-01-22 21:44:22 +00001868 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00001869 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1870
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001871 // Translate the given source location to make it point at the beginning of
1872 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00001873 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00001874
1875 // Guard against an invalid SourceLocation, or we may assert in one
1876 // of the following calls.
1877 if (SLoc.isInvalid())
1878 return clang_getNullCursor();
1879
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001880 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
1881 CXXUnit->getASTContext().getLangOptions());
1882
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001883 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1884 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001885 // FIXME: Would be great to have a "hint" cursor, then walk from that
1886 // hint cursor upward until we find a cursor whose source range encloses
1887 // the region of interest, rather than starting from the translation unit.
1888 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001889 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001890 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001891 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001892 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001893 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001894}
1895
Ted Kremenek73885552009-11-17 19:28:59 +00001896CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001897 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001898}
1899
1900unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001901 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001902}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001903
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001904unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001905 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1906}
1907
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001908unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001909 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1910}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001911
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001912unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001913 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1914}
1915
Douglas Gregor97b98722010-01-19 23:20:36 +00001916unsigned clang_isExpression(enum CXCursorKind K) {
1917 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1918}
1919
1920unsigned clang_isStatement(enum CXCursorKind K) {
1921 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1922}
1923
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001924unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1925 return K == CXCursor_TranslationUnit;
1926}
1927
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001928unsigned clang_isPreprocessing(enum CXCursorKind K) {
1929 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1930}
1931
Ted Kremenekad6eff62010-03-08 21:17:29 +00001932unsigned clang_isUnexposed(enum CXCursorKind K) {
1933 switch (K) {
1934 case CXCursor_UnexposedDecl:
1935 case CXCursor_UnexposedExpr:
1936 case CXCursor_UnexposedStmt:
1937 case CXCursor_UnexposedAttr:
1938 return true;
1939 default:
1940 return false;
1941 }
1942}
1943
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001944CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001945 return C.kind;
1946}
1947
Douglas Gregor98258af2010-01-18 22:46:11 +00001948CXSourceLocation clang_getCursorLocation(CXCursor C) {
1949 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001950 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001951 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001952 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1953 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001954 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001955 }
1956
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001957 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001958 std::pair<ObjCProtocolDecl *, SourceLocation> P
1959 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001960 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001961 }
1962
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001963 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001964 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1965 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001966 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001967 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001968
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001969 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001970 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001971 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001972 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001973
Douglas Gregorf46034a2010-01-18 23:41:10 +00001974 default:
1975 // FIXME: Need a way to enumerate all non-reference cases.
1976 llvm_unreachable("Missed a reference kind");
1977 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001978 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001979
1980 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001981 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001982 getLocationFromExpr(getCursorExpr(C)));
1983
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001984 if (C.kind == CXCursor_PreprocessingDirective) {
1985 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1986 return cxloc::translateSourceLocation(getCursorContext(C), L);
1987 }
Douglas Gregor48072312010-03-18 15:23:44 +00001988
1989 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001990 SourceLocation L
1991 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001992 return cxloc::translateSourceLocation(getCursorContext(C), L);
1993 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001994
1995 if (C.kind == CXCursor_MacroDefinition) {
1996 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1997 return cxloc::translateSourceLocation(getCursorContext(C), L);
1998 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001999
Ted Kremenek9a700d22010-05-12 06:16:13 +00002000 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002001 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002002
Douglas Gregorf46034a2010-01-18 23:41:10 +00002003 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002004 SourceLocation Loc = D->getLocation();
2005 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2006 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002007 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002008}
Douglas Gregora7bde202010-01-19 00:34:46 +00002009
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002010} // end extern "C"
2011
2012static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002013 if (clang_isReference(C.kind)) {
2014 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002015 case CXCursor_ObjCSuperClassRef:
2016 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002017
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002018 case CXCursor_ObjCProtocolRef:
2019 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002020
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002021 case CXCursor_ObjCClassRef:
2022 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002023
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002024 case CXCursor_TypeRef:
2025 return getCursorTypeRef(C).second;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002026
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002027 default:
2028 // FIXME: Need a way to enumerate all non-reference cases.
2029 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002030 }
2031 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002032
2033 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002034 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002035
2036 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002037 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002038
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002039 if (C.kind == CXCursor_PreprocessingDirective)
2040 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002041
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002042 if (C.kind == CXCursor_MacroInstantiation)
2043 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002044
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002045 if (C.kind == CXCursor_MacroDefinition)
2046 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002047
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002048 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2049 return getCursorDecl(C)->getSourceRange();
2050
2051 return SourceRange();
2052}
2053
2054extern "C" {
2055
2056CXSourceRange clang_getCursorExtent(CXCursor C) {
2057 SourceRange R = getRawCursorExtent(C);
2058 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002059 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002060
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002061 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002062}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002063
2064CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002065 if (clang_isInvalid(C.kind))
2066 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002067
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002068 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002069 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002070 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002071
Douglas Gregor97b98722010-01-19 23:20:36 +00002072 if (clang_isExpression(C.kind)) {
2073 Decl *D = getDeclFromExpr(getCursorExpr(C));
2074 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002075 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002076 return clang_getNullCursor();
2077 }
2078
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002079 if (C.kind == CXCursor_MacroInstantiation) {
2080 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2081 return MakeMacroDefinitionCursor(Def, CXXUnit);
2082 }
2083
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002084 if (!clang_isReference(C.kind))
2085 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002086
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002087 switch (C.kind) {
2088 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002089 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002090
2091 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002092 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002093
2094 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002095 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002096
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002097 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002098 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002099
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002100 default:
2101 // We would prefer to enumerate all non-reference cursor kinds here.
2102 llvm_unreachable("Unhandled reference cursor kind");
2103 break;
2104 }
2105 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002106
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002107 return clang_getNullCursor();
2108}
2109
Douglas Gregorb6998662010-01-19 19:34:47 +00002110CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002111 if (clang_isInvalid(C.kind))
2112 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002113
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002114 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002115
Douglas Gregorb6998662010-01-19 19:34:47 +00002116 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002117 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002118 C = clang_getCursorReferenced(C);
2119 WasReference = true;
2120 }
2121
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002122 if (C.kind == CXCursor_MacroInstantiation)
2123 return clang_getCursorReferenced(C);
2124
Douglas Gregorb6998662010-01-19 19:34:47 +00002125 if (!clang_isDeclaration(C.kind))
2126 return clang_getNullCursor();
2127
2128 Decl *D = getCursorDecl(C);
2129 if (!D)
2130 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002131
Douglas Gregorb6998662010-01-19 19:34:47 +00002132 switch (D->getKind()) {
2133 // Declaration kinds that don't really separate the notions of
2134 // declaration and definition.
2135 case Decl::Namespace:
2136 case Decl::Typedef:
2137 case Decl::TemplateTypeParm:
2138 case Decl::EnumConstant:
2139 case Decl::Field:
2140 case Decl::ObjCIvar:
2141 case Decl::ObjCAtDefsField:
2142 case Decl::ImplicitParam:
2143 case Decl::ParmVar:
2144 case Decl::NonTypeTemplateParm:
2145 case Decl::TemplateTemplateParm:
2146 case Decl::ObjCCategoryImpl:
2147 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002148 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002149 case Decl::LinkageSpec:
2150 case Decl::ObjCPropertyImpl:
2151 case Decl::FileScopeAsm:
2152 case Decl::StaticAssert:
2153 case Decl::Block:
2154 return C;
2155
2156 // Declaration kinds that don't make any sense here, but are
2157 // nonetheless harmless.
2158 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002159 break;
2160
2161 // Declaration kinds for which the definition is not resolvable.
2162 case Decl::UnresolvedUsingTypename:
2163 case Decl::UnresolvedUsingValue:
2164 break;
2165
2166 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002167 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2168 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002169
2170 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002171 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002172
2173 case Decl::Enum:
2174 case Decl::Record:
2175 case Decl::CXXRecord:
2176 case Decl::ClassTemplateSpecialization:
2177 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002178 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002179 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002180 return clang_getNullCursor();
2181
2182 case Decl::Function:
2183 case Decl::CXXMethod:
2184 case Decl::CXXConstructor:
2185 case Decl::CXXDestructor:
2186 case Decl::CXXConversion: {
2187 const FunctionDecl *Def = 0;
2188 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002189 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002190 return clang_getNullCursor();
2191 }
2192
2193 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002194 // Ask the variable if it has a definition.
2195 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2196 return MakeCXCursor(Def, CXXUnit);
2197 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002198 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002199
Douglas Gregorb6998662010-01-19 19:34:47 +00002200 case Decl::FunctionTemplate: {
2201 const FunctionDecl *Def = 0;
2202 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002203 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002204 return clang_getNullCursor();
2205 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002206
Douglas Gregorb6998662010-01-19 19:34:47 +00002207 case Decl::ClassTemplate: {
2208 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002209 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002210 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002211 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002212 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002213 return clang_getNullCursor();
2214 }
2215
2216 case Decl::Using: {
2217 UsingDecl *Using = cast<UsingDecl>(D);
2218 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002219 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2220 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002221 S != SEnd; ++S) {
2222 if (Def != clang_getNullCursor()) {
2223 // FIXME: We have no way to return multiple results.
2224 return clang_getNullCursor();
2225 }
2226
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002227 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002228 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002229 }
2230
2231 return Def;
2232 }
2233
2234 case Decl::UsingShadow:
2235 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002236 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002237 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002238
2239 case Decl::ObjCMethod: {
2240 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2241 if (Method->isThisDeclarationADefinition())
2242 return C;
2243
2244 // Dig out the method definition in the associated
2245 // @implementation, if we have it.
2246 // FIXME: The ASTs should make finding the definition easier.
2247 if (ObjCInterfaceDecl *Class
2248 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2249 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2250 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2251 Method->isInstanceMethod()))
2252 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002253 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002254
2255 return clang_getNullCursor();
2256 }
2257
2258 case Decl::ObjCCategory:
2259 if (ObjCCategoryImplDecl *Impl
2260 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002261 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002262 return clang_getNullCursor();
2263
2264 case Decl::ObjCProtocol:
2265 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2266 return C;
2267 return clang_getNullCursor();
2268
2269 case Decl::ObjCInterface:
2270 // There are two notions of a "definition" for an Objective-C
2271 // class: the interface and its implementation. When we resolved a
2272 // reference to an Objective-C class, produce the @interface as
2273 // the definition; when we were provided with the interface,
2274 // produce the @implementation as the definition.
2275 if (WasReference) {
2276 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2277 return C;
2278 } else if (ObjCImplementationDecl *Impl
2279 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002280 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002281 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002282
Douglas Gregorb6998662010-01-19 19:34:47 +00002283 case Decl::ObjCProperty:
2284 // FIXME: We don't really know where to find the
2285 // ObjCPropertyImplDecls that implement this property.
2286 return clang_getNullCursor();
2287
2288 case Decl::ObjCCompatibleAlias:
2289 if (ObjCInterfaceDecl *Class
2290 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2291 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002292 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002293
Douglas Gregorb6998662010-01-19 19:34:47 +00002294 return clang_getNullCursor();
2295
2296 case Decl::ObjCForwardProtocol: {
2297 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2298 if (Forward->protocol_size() == 1)
2299 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002300 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002301 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002302
2303 // FIXME: Cannot return multiple definitions.
2304 return clang_getNullCursor();
2305 }
2306
2307 case Decl::ObjCClass: {
2308 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2309 if (Class->size() == 1) {
2310 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2311 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002312 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002313 return clang_getNullCursor();
2314 }
2315
2316 // FIXME: Cannot return multiple definitions.
2317 return clang_getNullCursor();
2318 }
2319
2320 case Decl::Friend:
2321 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002322 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002323 return clang_getNullCursor();
2324
2325 case Decl::FriendTemplate:
2326 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002327 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002328 return clang_getNullCursor();
2329 }
2330
2331 return clang_getNullCursor();
2332}
2333
2334unsigned clang_isCursorDefinition(CXCursor C) {
2335 if (!clang_isDeclaration(C.kind))
2336 return 0;
2337
2338 return clang_getCursorDefinition(C) == C;
2339}
2340
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002341void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002342 const char **startBuf,
2343 const char **endBuf,
2344 unsigned *startLine,
2345 unsigned *startColumn,
2346 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002347 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002348 assert(getCursorDecl(C) && "CXCursor has null decl");
2349 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002350 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2351 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002352
Steve Naroff4ade6d62009-09-23 17:52:52 +00002353 SourceManager &SM = FD->getASTContext().getSourceManager();
2354 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2355 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2356 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2357 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2358 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2359 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2360}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002361
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002362void clang_enableStackTraces(void) {
2363 llvm::sys::PrintStackTraceOnErrorSignal();
2364}
2365
Ted Kremenekfb480492010-01-13 21:46:36 +00002366} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002367
Ted Kremenekfb480492010-01-13 21:46:36 +00002368//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002369// Token-based Operations.
2370//===----------------------------------------------------------------------===//
2371
2372/* CXToken layout:
2373 * int_data[0]: a CXTokenKind
2374 * int_data[1]: starting token location
2375 * int_data[2]: token length
2376 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002377 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002378 * otherwise unused.
2379 */
2380extern "C" {
2381
2382CXTokenKind clang_getTokenKind(CXToken CXTok) {
2383 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2384}
2385
2386CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2387 switch (clang_getTokenKind(CXTok)) {
2388 case CXToken_Identifier:
2389 case CXToken_Keyword:
2390 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002391 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2392 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002393
2394 case CXToken_Literal: {
2395 // We have stashed the starting pointer in the ptr_data field. Use it.
2396 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002397 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002398 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002399
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002400 case CXToken_Punctuation:
2401 case CXToken_Comment:
2402 break;
2403 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002404
2405 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002406 // deconstructing the source location.
2407 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2408 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002409 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002410
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002411 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2412 std::pair<FileID, unsigned> LocInfo
2413 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002414 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002415 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002416 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2417 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002418 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002419
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002420 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002421}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002422
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002423CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2424 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2425 if (!CXXUnit)
2426 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002427
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002428 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2429 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2430}
2431
2432CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2433 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002434 if (!CXXUnit)
2435 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002436
2437 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002438 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2439}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002440
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002441void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2442 CXToken **Tokens, unsigned *NumTokens) {
2443 if (Tokens)
2444 *Tokens = 0;
2445 if (NumTokens)
2446 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002447
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002448 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2449 if (!CXXUnit || !Tokens || !NumTokens)
2450 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002451
Douglas Gregorbdf60622010-03-05 21:16:25 +00002452 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2453
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002454 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002455 if (R.isInvalid())
2456 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002457
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002458 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2459 std::pair<FileID, unsigned> BeginLocInfo
2460 = SourceMgr.getDecomposedLoc(R.getBegin());
2461 std::pair<FileID, unsigned> EndLocInfo
2462 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002463
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002464 // Cannot tokenize across files.
2465 if (BeginLocInfo.first != EndLocInfo.first)
2466 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002467
2468 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002469 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002470 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002471 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002472 if (Invalid)
2473 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002474
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002475 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2476 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002477 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002478 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002479
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002480 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002481 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002482 llvm::SmallVector<CXToken, 32> CXTokens;
2483 Token Tok;
2484 do {
2485 // Lex the next token
2486 Lex.LexFromRawLexer(Tok);
2487 if (Tok.is(tok::eof))
2488 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002489
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002490 // Initialize the CXToken.
2491 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002492
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002493 // - Common fields
2494 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2495 CXTok.int_data[2] = Tok.getLength();
2496 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002497
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002498 // - Kind-specific fields
2499 if (Tok.isLiteral()) {
2500 CXTok.int_data[0] = CXToken_Literal;
2501 CXTok.ptr_data = (void *)Tok.getLiteralData();
2502 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002503 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002504 std::pair<FileID, unsigned> LocInfo
2505 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002506 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002507 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002508 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2509 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002510 return;
2511
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002512 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002513 IdentifierInfo *II
2514 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002515
2516 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2517 CXTok.int_data[0] = CXToken_Keyword;
2518 }
2519 else {
2520 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2521 CXToken_Identifier
2522 : CXToken_Keyword;
2523 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002524 CXTok.ptr_data = II;
2525 } else if (Tok.is(tok::comment)) {
2526 CXTok.int_data[0] = CXToken_Comment;
2527 CXTok.ptr_data = 0;
2528 } else {
2529 CXTok.int_data[0] = CXToken_Punctuation;
2530 CXTok.ptr_data = 0;
2531 }
2532 CXTokens.push_back(CXTok);
2533 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002534
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002535 if (CXTokens.empty())
2536 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002537
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002538 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2539 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2540 *NumTokens = CXTokens.size();
2541}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002542
Ted Kremenek6db61092010-05-05 00:55:15 +00002543void clang_disposeTokens(CXTranslationUnit TU,
2544 CXToken *Tokens, unsigned NumTokens) {
2545 free(Tokens);
2546}
2547
2548} // end: extern "C"
2549
2550//===----------------------------------------------------------------------===//
2551// Token annotation APIs.
2552//===----------------------------------------------------------------------===//
2553
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002554typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002555static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2556 CXCursor parent,
2557 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002558namespace {
2559class AnnotateTokensWorker {
2560 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002561 CXToken *Tokens;
2562 CXCursor *Cursors;
2563 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002564 unsigned TokIdx;
2565 CursorVisitor AnnotateVis;
2566 SourceManager &SrcMgr;
2567
2568 bool MoreTokens() const { return TokIdx < NumTokens; }
2569 unsigned NextToken() const { return TokIdx; }
2570 void AdvanceToken() { ++TokIdx; }
2571 SourceLocation GetTokenLoc(unsigned tokI) {
2572 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2573 }
2574
Ted Kremenek6db61092010-05-05 00:55:15 +00002575public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002576 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002577 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2578 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002579 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002580 NumTokens(numTokens), TokIdx(0),
2581 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2582 Decl::MaxPCHLevel, RegionOfInterest),
2583 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002584
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002585 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002586 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002587 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002588};
2589}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002590
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002591void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2592 // Walk the AST within the region of interest, annotating tokens
2593 // along the way.
2594 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002595
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002596 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2597 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2598 if (Pos != Annotated.end())
2599 Cursors[I] = Pos->second;
2600 }
2601
2602 // Finish up annotating any tokens left.
2603 if (!MoreTokens())
2604 return;
2605
2606 const CXCursor &C = clang_getNullCursor();
2607 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2608 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2609 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002610 }
2611}
2612
Ted Kremenek6db61092010-05-05 00:55:15 +00002613enum CXChildVisitResult
2614AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002615 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2616 // We can always annotate a preprocessing directive/macro instantiation.
2617 if (clang_isPreprocessing(cursor.kind)) {
2618 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002619 return CXChildVisit_Recurse;
2620 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002621
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002622 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00002623
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002624 if (cursorRange.isInvalid())
2625 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002626
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002627 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2628
Ted Kremeneka333c662010-05-12 05:29:33 +00002629 // Adjust the annotated range based specific declarations.
2630 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2631 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002632 Decl *D = cxcursor::getCursorDecl(cursor);
2633 // Don't visit synthesized ObjC methods, since they have no syntatic
2634 // representation in the source.
2635 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2636 if (MD->isSynthesized())
2637 return CXChildVisit_Continue;
2638 }
2639 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002640 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2641 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002642 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002643 if (TLoc.isValid() &&
2644 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002645 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002646 }
2647 }
2648 }
2649
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002650 const enum CXCursorKind K = clang_getCursorKind(parent);
2651 const CXCursor updateC =
2652 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2653 L.isMacroID())
2654 ? clang_getNullCursor() : parent;
2655
2656 while (MoreTokens()) {
2657 const unsigned I = NextToken();
2658 SourceLocation TokLoc = GetTokenLoc(I);
2659 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2660 case RangeBefore:
2661 Cursors[I] = updateC;
2662 AdvanceToken();
2663 continue;
2664 case RangeAfter:
2665 return CXChildVisit_Continue;
2666 case RangeOverlap:
2667 break;
2668 }
2669 break;
2670 }
2671
2672 // Visit children to get their cursor information.
2673 const unsigned BeforeChildren = NextToken();
2674 VisitChildren(cursor);
2675 const unsigned AfterChildren = NextToken();
2676
2677 // Adjust 'Last' to the last token within the extent of the cursor.
2678 while (MoreTokens()) {
2679 const unsigned I = NextToken();
2680 SourceLocation TokLoc = GetTokenLoc(I);
2681 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2682 case RangeBefore:
2683 assert(0 && "Infeasible");
2684 case RangeAfter:
2685 break;
2686 case RangeOverlap:
2687 Cursors[I] = updateC;
2688 AdvanceToken();
2689 continue;
2690 }
2691 break;
2692 }
2693 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002694
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002695 // Scan the tokens that are at the beginning of the cursor, but are not
2696 // capture by the child cursors.
2697
2698 // For AST elements within macros, rely on a post-annotate pass to
2699 // to correctly annotate the tokens with cursors. Otherwise we can
2700 // get confusing results of having tokens that map to cursors that really
2701 // are expanded by an instantiation.
2702 if (L.isMacroID())
2703 cursor = clang_getNullCursor();
2704
2705 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2706 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2707 break;
2708 Cursors[I] = cursor;
2709 }
2710 // Scan the tokens that are at the end of the cursor, but are not captured
2711 // but the child cursors.
2712 for (unsigned I = AfterChildren; I != Last; ++I)
2713 Cursors[I] = cursor;
2714
2715 TokIdx = Last;
2716 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002717}
2718
Ted Kremenek6db61092010-05-05 00:55:15 +00002719static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2720 CXCursor parent,
2721 CXClientData client_data) {
2722 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2723}
2724
2725extern "C" {
2726
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002727void clang_annotateTokens(CXTranslationUnit TU,
2728 CXToken *Tokens, unsigned NumTokens,
2729 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002730
2731 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002732 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002733
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002734 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002735 if (!CXXUnit) {
2736 // Any token we don't specifically annotate will have a NULL cursor.
2737 const CXCursor &C = clang_getNullCursor();
2738 for (unsigned I = 0; I != NumTokens; ++I)
2739 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002740 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002741 }
2742
Douglas Gregorbdf60622010-03-05 21:16:25 +00002743 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002744
Douglas Gregor0396f462010-03-19 05:22:59 +00002745 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002746 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002747 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2748 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002749 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
2750 clang_getTokenLocation(TU,
2751 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002752
Douglas Gregor0396f462010-03-19 05:22:59 +00002753 // A mapping from the source locations found when re-lexing or traversing the
2754 // region of interest to the corresponding cursors.
2755 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002756
2757 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002758 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002759 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2760 std::pair<FileID, unsigned> BeginLocInfo
2761 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2762 std::pair<FileID, unsigned> EndLocInfo
2763 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002764
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002765 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002766 bool Invalid = false;
2767 if (BeginLocInfo.first == EndLocInfo.first &&
2768 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2769 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002770 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2771 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002772 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002773 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002774 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002775
2776 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002777 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002778 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002779 Token Tok;
2780 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002781
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002782 reprocess:
2783 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2784 // We have found a preprocessing directive. Gobble it up so that we
2785 // don't see it while preprocessing these tokens later, but keep track of
2786 // all of the token locations inside this preprocessing directive so that
2787 // we can annotate them appropriately.
2788 //
2789 // FIXME: Some simple tests here could identify macro definitions and
2790 // #undefs, to provide specific cursor kinds for those.
2791 std::vector<SourceLocation> Locations;
2792 do {
2793 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002794 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002795 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002796
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002797 using namespace cxcursor;
2798 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002799 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2800 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002801 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002802 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2803 Annotated[Locations[I].getRawEncoding()] = Cursor;
2804 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002805
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002806 if (Tok.isAtStartOfLine())
2807 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002808
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002809 continue;
2810 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002811
Douglas Gregor48072312010-03-18 15:23:44 +00002812 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002813 break;
2814 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002815 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002816
Douglas Gregor0396f462010-03-19 05:22:59 +00002817 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002818 // a specific cursor.
2819 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2820 CXXUnit, RegionOfInterest);
2821 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002822}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002823} // end: extern "C"
2824
2825//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002826// Operations for querying linkage of a cursor.
2827//===----------------------------------------------------------------------===//
2828
2829extern "C" {
2830CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002831 if (!clang_isDeclaration(cursor.kind))
2832 return CXLinkage_Invalid;
2833
Ted Kremenek16b42592010-03-03 06:36:57 +00002834 Decl *D = cxcursor::getCursorDecl(cursor);
2835 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2836 switch (ND->getLinkage()) {
2837 case NoLinkage: return CXLinkage_NoLinkage;
2838 case InternalLinkage: return CXLinkage_Internal;
2839 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2840 case ExternalLinkage: return CXLinkage_External;
2841 };
2842
2843 return CXLinkage_Invalid;
2844}
2845} // end: extern "C"
2846
2847//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002848// Operations for querying language of a cursor.
2849//===----------------------------------------------------------------------===//
2850
2851static CXLanguageKind getDeclLanguage(const Decl *D) {
2852 switch (D->getKind()) {
2853 default:
2854 break;
2855 case Decl::ImplicitParam:
2856 case Decl::ObjCAtDefsField:
2857 case Decl::ObjCCategory:
2858 case Decl::ObjCCategoryImpl:
2859 case Decl::ObjCClass:
2860 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002861 case Decl::ObjCForwardProtocol:
2862 case Decl::ObjCImplementation:
2863 case Decl::ObjCInterface:
2864 case Decl::ObjCIvar:
2865 case Decl::ObjCMethod:
2866 case Decl::ObjCProperty:
2867 case Decl::ObjCPropertyImpl:
2868 case Decl::ObjCProtocol:
2869 return CXLanguage_ObjC;
2870 case Decl::CXXConstructor:
2871 case Decl::CXXConversion:
2872 case Decl::CXXDestructor:
2873 case Decl::CXXMethod:
2874 case Decl::CXXRecord:
2875 case Decl::ClassTemplate:
2876 case Decl::ClassTemplatePartialSpecialization:
2877 case Decl::ClassTemplateSpecialization:
2878 case Decl::Friend:
2879 case Decl::FriendTemplate:
2880 case Decl::FunctionTemplate:
2881 case Decl::LinkageSpec:
2882 case Decl::Namespace:
2883 case Decl::NamespaceAlias:
2884 case Decl::NonTypeTemplateParm:
2885 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002886 case Decl::TemplateTemplateParm:
2887 case Decl::TemplateTypeParm:
2888 case Decl::UnresolvedUsingTypename:
2889 case Decl::UnresolvedUsingValue:
2890 case Decl::Using:
2891 case Decl::UsingDirective:
2892 case Decl::UsingShadow:
2893 return CXLanguage_CPlusPlus;
2894 }
2895
2896 return CXLanguage_C;
2897}
2898
2899extern "C" {
2900CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2901 if (clang_isDeclaration(cursor.kind))
2902 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2903
2904 return CXLanguage_Invalid;
2905}
2906} // end: extern "C"
2907
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002908
2909//===----------------------------------------------------------------------===//
2910// C++ AST instrospection.
2911//===----------------------------------------------------------------------===//
2912
2913extern "C" {
2914unsigned clang_CXXMethod_isStatic(CXCursor C) {
2915 if (!clang_isDeclaration(C.kind))
2916 return 0;
2917 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
2918 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00002919}
Ted Kremenekb12903e2010-05-18 22:32:15 +00002920
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002921} // end: extern "C"
2922
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002923//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002924// CXString Operations.
2925//===----------------------------------------------------------------------===//
2926
2927extern "C" {
2928const char *clang_getCString(CXString string) {
2929 return string.Spelling;
2930}
2931
2932void clang_disposeString(CXString string) {
2933 if (string.MustFreeString && string.Spelling)
2934 free((void*)string.Spelling);
2935}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002936
Ted Kremenekfb480492010-01-13 21:46:36 +00002937} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002938
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002939namespace clang { namespace cxstring {
2940CXString createCXString(const char *String, bool DupString){
2941 CXString Str;
2942 if (DupString) {
2943 Str.Spelling = strdup(String);
2944 Str.MustFreeString = 1;
2945 } else {
2946 Str.Spelling = String;
2947 Str.MustFreeString = 0;
2948 }
2949 return Str;
2950}
2951
2952CXString createCXString(llvm::StringRef String, bool DupString) {
2953 CXString Result;
2954 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2955 char *Spelling = (char *)malloc(String.size() + 1);
2956 memmove(Spelling, String.data(), String.size());
2957 Spelling[String.size()] = 0;
2958 Result.Spelling = Spelling;
2959 Result.MustFreeString = 1;
2960 } else {
2961 Result.Spelling = String.data();
2962 Result.MustFreeString = 0;
2963 }
2964 return Result;
2965}
2966}}
2967
Ted Kremenek04bb7162010-01-22 22:44:15 +00002968//===----------------------------------------------------------------------===//
2969// Misc. utility functions.
2970//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002971
Ted Kremenek04bb7162010-01-22 22:44:15 +00002972extern "C" {
2973
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002974CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002975 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002976}
2977
2978} // end: extern "C"