blob: 344960f813c70ffda68e3ba3fbed65f4d4a78f3c [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 Gregor6cd24e22010-07-29 00:26:18 +0000347 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000348 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000349 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000350 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000351 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000352 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000353 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000354 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000355};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000356
Ted Kremenekab188932010-01-05 19:32:54 +0000357} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000358
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000359static SourceRange getRawCursorExtent(CXCursor C);
360
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000361RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000362 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
363}
364
Douglas Gregorb1373d02010-01-20 20:59:29 +0000365/// \brief Visit the given cursor and, if requested by the visitor,
366/// its children.
367///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000368/// \param Cursor the cursor to visit.
369///
370/// \param CheckRegionOfInterest if true, then the caller already checked that
371/// this cursor is within the region of interest.
372///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000373/// \returns true if the visitation should be aborted, false if it
374/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000375bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376 if (clang_isInvalid(Cursor.kind))
377 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000378
Douglas Gregorb1373d02010-01-20 20:59:29 +0000379 if (clang_isDeclaration(Cursor.kind)) {
380 Decl *D = getCursorDecl(Cursor);
381 assert(D && "Invalid declaration cursor");
382 if (D->getPCHLevel() > MaxPCHLevel)
383 return false;
384
385 if (D->isImplicit())
386 return false;
387 }
388
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000389 // If we have a range of interest, and this cursor doesn't intersect with it,
390 // we're done.
391 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000392 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000393 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000394 return false;
395 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000396
Douglas Gregorb1373d02010-01-20 20:59:29 +0000397 switch (Visitor(Cursor, Parent, ClientData)) {
398 case CXChildVisit_Break:
399 return true;
400
401 case CXChildVisit_Continue:
402 return false;
403
404 case CXChildVisit_Recurse:
405 return VisitChildren(Cursor);
406 }
407
Douglas Gregorfd643772010-01-25 16:45:46 +0000408 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000409}
410
Douglas Gregor788f5a12010-03-20 00:41:21 +0000411std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
412CursorVisitor::getPreprocessedEntities() {
413 PreprocessingRecord &PPRec
414 = *TU->getPreprocessor().getPreprocessingRecord();
415
416 bool OnlyLocalDecls
417 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
418
419 // There is no region of interest; we have to walk everything.
420 if (RegionOfInterest.isInvalid())
421 return std::make_pair(PPRec.begin(OnlyLocalDecls),
422 PPRec.end(OnlyLocalDecls));
423
424 // Find the file in which the region of interest lands.
425 SourceManager &SM = TU->getSourceManager();
426 std::pair<FileID, unsigned> Begin
427 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
428 std::pair<FileID, unsigned> End
429 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
430
431 // The region of interest spans files; we have to walk everything.
432 if (Begin.first != End.first)
433 return std::make_pair(PPRec.begin(OnlyLocalDecls),
434 PPRec.end(OnlyLocalDecls));
435
436 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
437 = TU->getPreprocessedEntitiesByFile();
438 if (ByFileMap.empty()) {
439 // Build the mapping from files to sets of preprocessed entities.
440 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
441 EEnd = PPRec.end(OnlyLocalDecls);
442 E != EEnd; ++E) {
443 std::pair<FileID, unsigned> P
444 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
445 ByFileMap[P.first].push_back(*E);
446 }
447 }
448
449 return std::make_pair(ByFileMap[Begin.first].begin(),
450 ByFileMap[Begin.first].end());
451}
452
Douglas Gregorb1373d02010-01-20 20:59:29 +0000453/// \brief Visit the children of the given cursor.
454///
455/// \returns true if the visitation should be aborted, false if it
456/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000457bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000458 if (clang_isReference(Cursor.kind)) {
459 // By definition, references have no children.
460 return false;
461 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000462
463 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000464 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000465 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000466
Douglas Gregorb1373d02010-01-20 20:59:29 +0000467 if (clang_isDeclaration(Cursor.kind)) {
468 Decl *D = getCursorDecl(Cursor);
469 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000470 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000471 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000472
Douglas Gregora59e3902010-01-21 23:27:09 +0000473 if (clang_isStatement(Cursor.kind))
474 return Visit(getCursorStmt(Cursor));
475 if (clang_isExpression(Cursor.kind))
476 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000477
Douglas Gregorb1373d02010-01-20 20:59:29 +0000478 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000479 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000480 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
481 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000482 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
483 TLEnd = CXXUnit->top_level_end();
484 TL != TLEnd; ++TL) {
485 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000486 return true;
487 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000488 } else if (VisitDeclContext(
489 CXXUnit->getASTContext().getTranslationUnitDecl()))
490 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000491
Douglas Gregor0396f462010-03-19 05:22:59 +0000492 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000493 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000494 // FIXME: Once we have the ability to deserialize a preprocessing record,
495 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000496 PreprocessingRecord::iterator E, EEnd;
497 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000498 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
499 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
500 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000501
Douglas Gregor0396f462010-03-19 05:22:59 +0000502 continue;
503 }
504
505 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
506 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
507 return true;
508
509 continue;
510 }
511 }
512 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000513 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000514 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000515
Douglas Gregorb1373d02010-01-20 20:59:29 +0000516 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000517 return false;
518}
519
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000520bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000521 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
522 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000523
Ted Kremenek664cffd2010-07-22 11:30:19 +0000524 if (Stmt *Body = B->getBody())
525 return Visit(MakeCXCursor(Body, StmtParent, TU));
526
527 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000528}
529
Douglas Gregorb1373d02010-01-20 20:59:29 +0000530bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000531 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000532 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000533
Ted Kremenek23173d72010-05-18 21:09:07 +0000534 Decl *D = *I;
535 if (D->getLexicalDeclContext() != DC)
536 continue;
537
538 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000539
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000540 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000541 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000542 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000543 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000544
545 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000546 case RangeBefore:
547 // This declaration comes before the region of interest; skip it.
548 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000549
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000550 case RangeAfter:
551 // This declaration comes after the region of interest; we're done.
552 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000553
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000554 case RangeOverlap:
555 // This declaration overlaps the region of interest; visit it.
556 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000557 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000558 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000559
Daniel Dunbard52864b2010-02-14 10:02:57 +0000560 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000561 return true;
562 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000563
Douglas Gregorb1373d02010-01-20 20:59:29 +0000564 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000565}
566
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000567bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
568 llvm_unreachable("Translation units are visited directly by Visit()");
569 return false;
570}
571
572bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
573 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
574 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000575
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000576 return false;
577}
578
579bool CursorVisitor::VisitTagDecl(TagDecl *D) {
580 return VisitDeclContext(D);
581}
582
583bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
584 if (Expr *Init = D->getInitExpr())
585 return Visit(MakeCXCursor(Init, StmtParent, TU));
586 return false;
587}
588
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000589bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
590 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
591 if (Visit(TSInfo->getTypeLoc()))
592 return true;
593
594 return false;
595}
596
Douglas Gregorb1373d02010-01-20 20:59:29 +0000597bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000598 if (VisitDeclaratorDecl(ND))
599 return true;
600
Douglas Gregora59e3902010-01-21 23:27:09 +0000601 if (ND->isThisDeclarationADefinition() &&
602 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
603 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000604
Douglas Gregorb1373d02010-01-20 20:59:29 +0000605 return false;
606}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
609 if (VisitDeclaratorDecl(D))
610 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000611
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000612 if (Expr *BitWidth = D->getBitWidth())
613 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000614
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000615 return false;
616}
617
618bool CursorVisitor::VisitVarDecl(VarDecl *D) {
619 if (VisitDeclaratorDecl(D))
620 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000621
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000622 if (Expr *Init = D->getInit())
623 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000624
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000625 return false;
626}
627
628bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000629 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
630 if (Visit(TSInfo->getTypeLoc()))
631 return true;
632
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000633 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000634 PEnd = ND->param_end();
635 P != PEnd; ++P) {
636 if (Visit(MakeCXCursor(*P, TU)))
637 return true;
638 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000639
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000640 if (ND->isThisDeclarationADefinition() &&
641 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
642 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000643
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000644 return false;
645}
646
Douglas Gregora59e3902010-01-21 23:27:09 +0000647bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
648 return VisitDeclContext(D);
649}
650
Douglas Gregorb1373d02010-01-20 20:59:29 +0000651bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000652 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
653 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000654 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000655
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000656 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
657 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
658 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000659 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000660 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000661
Douglas Gregora59e3902010-01-21 23:27:09 +0000662 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000663}
664
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000665bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
666 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
667 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
668 E = PID->protocol_end(); I != E; ++I, ++PL)
669 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
670 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000671
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000672 return VisitObjCContainerDecl(PID);
673}
674
Ted Kremenek23173d72010-05-18 21:09:07 +0000675bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000676 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
677 return true;
678
Ted Kremenek23173d72010-05-18 21:09:07 +0000679 // FIXME: This implements a workaround with @property declarations also being
680 // installed in the DeclContext for the @interface. Eventually this code
681 // should be removed.
682 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
683 if (!CDecl || !CDecl->IsClassExtension())
684 return false;
685
686 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
687 if (!ID)
688 return false;
689
690 IdentifierInfo *PropertyId = PD->getIdentifier();
691 ObjCPropertyDecl *prevDecl =
692 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
693
694 if (!prevDecl)
695 return false;
696
697 // Visit synthesized methods since they will be skipped when visiting
698 // the @interface.
699 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
700 if (MD->isSynthesized())
701 if (Visit(MakeCXCursor(MD, TU)))
702 return true;
703
704 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
705 if (MD->isSynthesized())
706 if (Visit(MakeCXCursor(MD, TU)))
707 return true;
708
709 return false;
710}
711
Douglas Gregorb1373d02010-01-20 20:59:29 +0000712bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000713 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000714 if (D->getSuperClass() &&
715 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000716 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000717 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000718 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000719
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000720 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
721 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
722 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000723 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000724 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000725
Douglas Gregora59e3902010-01-21 23:27:09 +0000726 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000727}
728
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000729bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
730 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000731}
732
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000733bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000734 // 'ID' could be null when dealing with invalid code.
735 if (ObjCInterfaceDecl *ID = D->getClassInterface())
736 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
737 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000738
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000739 return VisitObjCImplDecl(D);
740}
741
742bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
743#if 0
744 // Issue callbacks for super class.
745 // FIXME: No source location information!
746 if (D->getSuperClass() &&
747 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000748 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000749 TU)))
750 return true;
751#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000752
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000753 return VisitObjCImplDecl(D);
754}
755
756bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
757 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
758 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
759 E = D->protocol_end();
760 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000761 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000762 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000763
764 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000765}
766
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000767bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
768 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
769 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
770 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000771
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000772 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000773}
774
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000775bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
776 return VisitDeclContext(D);
777}
778
Ted Kremeneka0536d82010-05-07 01:04:29 +0000779bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
780 return VisitDeclContext(D);
781}
782
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000783bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
784 ASTContext &Context = TU->getASTContext();
785
786 // Some builtin types (such as Objective-C's "id", "sel", and
787 // "Class") have associated declarations. Create cursors for those.
788 QualType VisitType;
789 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000790 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000791 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000792 case BuiltinType::Char_U:
793 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000794 case BuiltinType::Char16:
795 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000796 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000797 case BuiltinType::UInt:
798 case BuiltinType::ULong:
799 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000800 case BuiltinType::UInt128:
801 case BuiltinType::Char_S:
802 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000803 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000804 case BuiltinType::Short:
805 case BuiltinType::Int:
806 case BuiltinType::Long:
807 case BuiltinType::LongLong:
808 case BuiltinType::Int128:
809 case BuiltinType::Float:
810 case BuiltinType::Double:
811 case BuiltinType::LongDouble:
812 case BuiltinType::NullPtr:
813 case BuiltinType::Overload:
814 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000815 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000816
817 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000818 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000819
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000820 case BuiltinType::ObjCId:
821 VisitType = Context.getObjCIdType();
822 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000823
824 case BuiltinType::ObjCClass:
825 VisitType = Context.getObjCClassType();
826 break;
827
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000828 case BuiltinType::ObjCSel:
829 VisitType = Context.getObjCSelType();
830 break;
831 }
832
833 if (!VisitType.isNull()) {
834 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000835 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000836 TU));
837 }
838
839 return false;
840}
841
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000842bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
843 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
844}
845
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000846bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
847 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
848}
849
850bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
851 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
852}
853
854bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
855 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
856 return true;
857
John McCallc12c5bb2010-05-15 11:32:37 +0000858 return false;
859}
860
861bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
862 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
863 return true;
864
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000865 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
866 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
867 TU)))
868 return true;
869 }
870
871 return false;
872}
873
874bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +0000875 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000876}
877
878bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
879 return Visit(TL.getPointeeLoc());
880}
881
882bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
883 return Visit(TL.getPointeeLoc());
884}
885
886bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
887 return Visit(TL.getPointeeLoc());
888}
889
890bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000891 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000892}
893
894bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000895 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000896}
897
898bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
899 if (Visit(TL.getResultLoc()))
900 return true;
901
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000902 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000903 if (Decl *D = TL.getArg(I))
904 if (Visit(MakeCXCursor(D, TU)))
905 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000906
907 return false;
908}
909
910bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
911 if (Visit(TL.getElementLoc()))
912 return true;
913
914 if (Expr *Size = TL.getSizeExpr())
915 return Visit(MakeCXCursor(Size, StmtParent, TU));
916
917 return false;
918}
919
Douglas Gregor2332c112010-01-21 20:48:56 +0000920bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
921 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
922}
923
924bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
925 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
926 return Visit(TSInfo->getTypeLoc());
927
928 return false;
929}
930
Douglas Gregora59e3902010-01-21 23:27:09 +0000931bool CursorVisitor::VisitStmt(Stmt *S) {
932 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
933 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000934 if (Stmt *C = *Child)
935 if (Visit(MakeCXCursor(C, StmtParent, TU)))
936 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +0000937 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000938
Douglas Gregora59e3902010-01-21 23:27:09 +0000939 return false;
940}
941
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000942bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
943 // Specially handle CaseStmts because they can be nested, e.g.:
944 //
945 // case 1:
946 // case 2:
947 //
948 // In this case the second CaseStmt is the child of the first. Walking
949 // these recursively can blow out the stack.
950 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
951 while (true) {
952 // Set the Parent field to Cursor, then back to its old value once we're
953 // done.
954 SetParentRAII SetParent(Parent, StmtParent, Cursor);
955
956 if (Stmt *LHS = S->getLHS())
957 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
958 return true;
959 if (Stmt *RHS = S->getRHS())
960 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
961 return true;
962 if (Stmt *SubStmt = S->getSubStmt()) {
963 if (!isa<CaseStmt>(SubStmt))
964 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
965
966 // Specially handle 'CaseStmt' so that we don't blow out the stack.
967 CaseStmt *CS = cast<CaseStmt>(SubStmt);
968 Cursor = MakeCXCursor(CS, StmtParent, TU);
969 if (RegionOfInterest.isValid()) {
970 SourceRange Range = CS->getSourceRange();
971 if (Range.isInvalid() || CompareRegionOfInterest(Range))
972 return false;
973 }
974
975 switch (Visitor(Cursor, Parent, ClientData)) {
976 case CXChildVisit_Break: return true;
977 case CXChildVisit_Continue: return false;
978 case CXChildVisit_Recurse:
979 // Perform tail-recursion manually.
980 S = CS;
981 continue;
982 }
983 }
984 return false;
985 }
986}
987
Douglas Gregora59e3902010-01-21 23:27:09 +0000988bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
989 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
990 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000991 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000992 return true;
993 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000994
Douglas Gregora59e3902010-01-21 23:27:09 +0000995 return false;
996}
997
Douglas Gregorf5bab412010-01-22 01:00:11 +0000998bool CursorVisitor::VisitIfStmt(IfStmt *S) {
999 if (VarDecl *Var = S->getConditionVariable()) {
1000 if (Visit(MakeCXCursor(Var, TU)))
1001 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001002 }
1003
Douglas Gregor263b47b2010-01-25 16:12:32 +00001004 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1005 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001006 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1007 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001008 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1009 return true;
1010
1011 return false;
1012}
1013
1014bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1015 if (VarDecl *Var = S->getConditionVariable()) {
1016 if (Visit(MakeCXCursor(Var, TU)))
1017 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001018 }
1019
Douglas Gregor263b47b2010-01-25 16:12:32 +00001020 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1021 return true;
1022 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1023 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001024
Douglas Gregor263b47b2010-01-25 16:12:32 +00001025 return false;
1026}
1027
1028bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1029 if (VarDecl *Var = S->getConditionVariable()) {
1030 if (Visit(MakeCXCursor(Var, TU)))
1031 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001032 }
1033
Douglas Gregor263b47b2010-01-25 16:12:32 +00001034 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1035 return true;
1036 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001037 return true;
1038
Douglas Gregor263b47b2010-01-25 16:12:32 +00001039 return false;
1040}
1041
1042bool CursorVisitor::VisitForStmt(ForStmt *S) {
1043 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1044 return true;
1045 if (VarDecl *Var = S->getConditionVariable()) {
1046 if (Visit(MakeCXCursor(Var, TU)))
1047 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001048 }
1049
Douglas Gregor263b47b2010-01-25 16:12:32 +00001050 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1051 return true;
1052 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1053 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001054 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1055 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001056
Douglas Gregorf5bab412010-01-22 01:00:11 +00001057 return false;
1058}
1059
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001060bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1061 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1062 return true;
1063
1064 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1065 return true;
1066
1067 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1068 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1069 return true;
1070
1071 return false;
1072}
1073
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001074bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1075 return Visit(B->getBlockDecl());
1076}
1077
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001078bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1079 // FIXME: Visit fields as well?
1080 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1081 return true;
1082
1083 return VisitExpr(E);
1084}
1085
Douglas Gregor336fd812010-01-23 00:40:08 +00001086bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1087 if (E->isArgumentType()) {
1088 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1089 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001090
Douglas Gregor336fd812010-01-23 00:40:08 +00001091 return false;
1092 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001093
Douglas Gregor336fd812010-01-23 00:40:08 +00001094 return VisitExpr(E);
1095}
1096
1097bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1098 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1099 if (Visit(TSInfo->getTypeLoc()))
1100 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001101
Douglas Gregor336fd812010-01-23 00:40:08 +00001102 return VisitCastExpr(E);
1103}
1104
1105bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1106 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1107 if (Visit(TSInfo->getTypeLoc()))
1108 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001109
Douglas Gregor336fd812010-01-23 00:40:08 +00001110 return VisitExpr(E);
1111}
1112
Douglas Gregorc2350e52010-03-08 16:40:19 +00001113bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001114 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1115 if (Visit(TSInfo->getTypeLoc()))
1116 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001117
1118 return VisitExpr(E);
1119}
1120
Douglas Gregor81d34662010-04-20 15:39:42 +00001121bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1122 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1123}
1124
1125
Ted Kremenek09dfa372010-02-18 05:46:33 +00001126bool CursorVisitor::VisitAttributes(Decl *D) {
1127 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1128 if (Visit(MakeCXCursor(A, D, TU)))
1129 return true;
1130
1131 return false;
1132}
1133
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001134extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001135CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1136 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +00001137 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001138 if (excludeDeclarationsFromPCH)
1139 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001140 if (displayDiagnostics)
1141 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001142 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001143}
1144
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001145void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001146 if (CIdx)
1147 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001148 if (getenv("LIBCLANG_TIMING"))
1149 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001150}
1151
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001152void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001153 if (CIdx) {
1154 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1155 CXXIdx->setUseExternalASTGeneration(value);
1156 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001157}
1158
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001159CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001160 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001161 if (!CIdx)
1162 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001163
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001164 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001165
Douglas Gregor28019772010-04-05 23:52:57 +00001166 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1167 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001168 CXXIdx->getOnlyLocalDecls(),
1169 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001170}
1171
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001172CXTranslationUnit
1173clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1174 const char *source_filename,
1175 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001176 const char **command_line_args,
1177 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001178 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001179 return clang_parseTranslationUnit(CIdx, source_filename,
1180 command_line_args, num_command_line_args,
1181 unsaved_files, num_unsaved_files,
1182 CXTranslationUnit_DetailedPreprocessingRecord);
1183}
1184
1185CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1186 const char *source_filename,
1187 const char **command_line_args,
1188 int num_command_line_args,
1189 struct CXUnsavedFile *unsaved_files,
1190 unsigned num_unsaved_files,
1191 unsigned options) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001192 if (!CIdx)
1193 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001194
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001195 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1196
Douglas Gregor44c181a2010-07-23 00:33:23 +00001197 // The "editing" option implies other options.
1198 if (options & CXTranslationUnit_Editing)
1199 options |= CXTranslationUnit_PrecompiledPreamble;
1200 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001201 bool CompleteTranslationUnit
1202 = ((options & CXTranslationUnit_Incomplete) == 0);
1203
Douglas Gregor5352ac02010-01-28 00:27:43 +00001204 // Configure the diagnostics.
1205 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001206 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1207 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001208
Douglas Gregor4db64a42010-01-23 00:14:00 +00001209 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1210 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001211 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001212 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001213 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001214 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1215 Buffer));
1216 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001217
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001218 if (!CXXIdx->getUseExternalASTGeneration()) {
1219 llvm::SmallVector<const char *, 16> Args;
1220
1221 // The 'source_filename' argument is optional. If the caller does not
1222 // specify it then it is assumed that the source file is specified
1223 // in the actual argument list.
1224 if (source_filename)
1225 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001226
1227 // Since the Clang C library is primarily used by batch tools dealing with
1228 // (often very broken) source code, where spell-checking can have a
1229 // significant negative impact on performance (particularly when
1230 // precompiled headers are involved), we disable it by default.
1231 // Note that we place this argument early in the list, so that it can be
1232 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001233 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001234
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001235 Args.insert(Args.end(), command_line_args,
1236 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001237
Douglas Gregor44c181a2010-07-23 00:33:23 +00001238 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001239 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1240 Args.push_back("-Xclang");
1241 Args.push_back("-detailed-preprocessing-record");
1242 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001243
Douglas Gregor5352ac02010-01-28 00:27:43 +00001244 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001245
Ted Kremenek29b72842010-01-07 22:49:05 +00001246#ifdef USE_CRASHTRACER
1247 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001248#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001249
Daniel Dunbar94220972009-12-05 02:17:18 +00001250 llvm::OwningPtr<ASTUnit> Unit(
1251 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001252 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001253 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001254 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001255 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001256 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001257 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001258 PrecompilePreamble,
1259 CompleteTranslationUnit));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001260
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001261 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001262 // Make sure to check that 'Unit' is non-NULL.
1263 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001264 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1265 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001266 D != DEnd; ++D) {
1267 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001268 CXString Msg = clang_formatDiagnostic(&Diag,
1269 clang_defaultDiagnosticDisplayOptions());
1270 fprintf(stderr, "%s\n", clang_getCString(Msg));
1271 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001272 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001273#ifdef LLVM_ON_WIN32
1274 // On Windows, force a flush, since there may be multiple copies of
1275 // stderr and stdout in the file system, all with different buffers
1276 // but writing to the same device.
1277 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001278#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001279 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001280 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001281
1282 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001283 }
1284
Ted Kremenek139ba862009-10-22 00:03:57 +00001285 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001286 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001287
Ted Kremenek139ba862009-10-22 00:03:57 +00001288 // First add the complete path to the 'clang' executable.
1289 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001290 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001291
Ted Kremenek139ba862009-10-22 00:03:57 +00001292 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001293 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001294
Ted Kremenek139ba862009-10-22 00:03:57 +00001295 // The 'source_filename' argument is optional. If the caller does not
1296 // specify it then it is assumed that the source file is specified
1297 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001298 if (source_filename)
1299 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001300
Steve Naroff37b5ac22009-10-15 20:50:09 +00001301 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001302 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001303 char astTmpFile[L_tmpnam];
1304 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001305
1306 // Since the Clang C library is primarily used by batch tools dealing with
1307 // (often very broken) source code, where spell-checking can have a
1308 // significant negative impact on performance (particularly when
1309 // precompiled headers are involved), we disable it by default.
1310 // Note that we place this argument early in the list, so that it can be
1311 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001312 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001313
Douglas Gregor4db64a42010-01-23 00:14:00 +00001314 // Remap any unsaved files to temporary files.
1315 std::vector<llvm::sys::Path> TemporaryFiles;
1316 std::vector<std::string> RemapArgs;
1317 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1318 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001319
Douglas Gregor4db64a42010-01-23 00:14:00 +00001320 // The pointers into the elements of RemapArgs are stable because we
1321 // won't be adding anything to RemapArgs after this point.
1322 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1323 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001324
Ted Kremenek139ba862009-10-22 00:03:57 +00001325 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1326 for (int i = 0; i < num_command_line_args; ++i)
1327 if (const char *arg = command_line_args[i]) {
1328 if (strcmp(arg, "-o") == 0) {
1329 ++i; // Also skip the matching argument.
1330 continue;
1331 }
1332 if (strcmp(arg, "-emit-ast") == 0 ||
1333 strcmp(arg, "-c") == 0 ||
1334 strcmp(arg, "-fsyntax-only") == 0) {
1335 continue;
1336 }
1337
1338 // Keep the argument.
1339 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001340 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001341
Douglas Gregord93256e2010-01-28 06:00:51 +00001342 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001343 char tmpFileResults[L_tmpnam];
1344 char *tmpResultsFileName = tmpnam(tmpFileResults);
1345 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001346 TemporaryFiles.push_back(DiagnosticsFile);
1347 argv.push_back("-fdiagnostics-binary");
1348
Douglas Gregor44c181a2010-07-23 00:33:23 +00001349 // Do we need the detailed preprocessing record?
1350 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1351 argv.push_back("-Xclang");
1352 argv.push_back("-detailed-preprocessing-record");
1353 }
1354
Ted Kremenek139ba862009-10-22 00:03:57 +00001355 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001356 argv.push_back(NULL);
1357
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001358 // Invoke 'clang'.
1359 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1360 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001361 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001362 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1363 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001364 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001365 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001366 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001367
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001368 if (!ErrMsg.empty()) {
1369 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001370 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001371 I != E; ++I) {
1372 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001373 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001374 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001375 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001376
Daniel Dunbar32141c82010-02-23 20:23:45 +00001377 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001378 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001379
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001380 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001381 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001382 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001383 RemappedFiles.size(),
1384 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001385 if (ATU) {
1386 LoadSerializedDiagnostics(DiagnosticsFile,
1387 num_unsaved_files, unsaved_files,
1388 ATU->getFileManager(),
1389 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001390 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001391 } else if (CXXIdx->getDisplayDiagnostics()) {
1392 // We failed to load the ASTUnit, but we can still deserialize the
1393 // diagnostics and emit them.
1394 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001395 Diagnostic Diag;
1396 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001397 // FIXME: Faked LangOpts!
1398 LangOptions LangOpts;
1399 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1400 LoadSerializedDiagnostics(DiagnosticsFile,
1401 num_unsaved_files, unsaved_files,
1402 FileMgr, SourceMgr, Diags);
1403 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1404 DEnd = Diags.end();
1405 D != DEnd; ++D) {
1406 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001407 CXString Msg = clang_formatDiagnostic(&Diag,
1408 clang_defaultDiagnosticDisplayOptions());
1409 fprintf(stderr, "%s\n", clang_getCString(Msg));
1410 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001411 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001412
1413#ifdef LLVM_ON_WIN32
1414 // On Windows, force a flush, since there may be multiple copies of
1415 // stderr and stdout in the file system, all with different buffers
1416 // but writing to the same device.
1417 fflush(stderr);
1418#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001419 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001420
Douglas Gregor313e26c2010-02-18 23:35:40 +00001421 if (ATU) {
1422 // Make the translation unit responsible for destroying all temporary files.
1423 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1424 ATU->addTemporaryFile(TemporaryFiles[i]);
1425 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1426 } else {
1427 // Destroy all of the temporary files now; they can't be referenced any
1428 // longer.
1429 llvm::sys::Path(astTmpFile).eraseFromDisk();
1430 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1431 TemporaryFiles[i].eraseFromDisk();
1432 }
1433
Steve Naroffe19944c2009-10-15 22:23:48 +00001434 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001435}
1436
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001437void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001438 if (CTUnit)
1439 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001440}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001441
Douglas Gregorabc563f2010-07-19 21:46:24 +00001442int clang_reparseTranslationUnit(CXTranslationUnit TU,
1443 unsigned num_unsaved_files,
1444 struct CXUnsavedFile *unsaved_files) {
1445 if (!TU)
1446 return 1;
1447
1448 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1449 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1450 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1451 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001452 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001453 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1454 Buffer));
1455 }
1456
1457 return static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1458 RemappedFiles.size())? 1 : 0;
1459}
Douglas Gregordf95a132010-08-09 20:45:32 +00001460
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001461CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001462 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001463 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001464
Steve Naroff77accc12009-09-03 18:19:54 +00001465 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001466 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001467}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001468
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001469CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001470 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001471 return Result;
1472}
1473
Ted Kremenekfb480492010-01-13 21:46:36 +00001474} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001475
Ted Kremenekfb480492010-01-13 21:46:36 +00001476//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001477// CXSourceLocation and CXSourceRange Operations.
1478//===----------------------------------------------------------------------===//
1479
Douglas Gregorb9790342010-01-22 21:44:22 +00001480extern "C" {
1481CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001482 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001483 return Result;
1484}
1485
1486unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001487 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1488 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1489 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001490}
1491
1492CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1493 CXFile file,
1494 unsigned line,
1495 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001496 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001497 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001498
Douglas Gregorb9790342010-01-22 21:44:22 +00001499 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1500 SourceLocation SLoc
1501 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001502 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001503 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001504
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001505 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001506}
1507
Douglas Gregor5352ac02010-01-28 00:27:43 +00001508CXSourceRange clang_getNullRange() {
1509 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1510 return Result;
1511}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001512
Douglas Gregor5352ac02010-01-28 00:27:43 +00001513CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1514 if (begin.ptr_data[0] != end.ptr_data[0] ||
1515 begin.ptr_data[1] != end.ptr_data[1])
1516 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001517
1518 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001519 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001520 return Result;
1521}
1522
Douglas Gregor46766dc2010-01-26 19:19:08 +00001523void clang_getInstantiationLocation(CXSourceLocation location,
1524 CXFile *file,
1525 unsigned *line,
1526 unsigned *column,
1527 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001528 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1529
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001530 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001531 if (file)
1532 *file = 0;
1533 if (line)
1534 *line = 0;
1535 if (column)
1536 *column = 0;
1537 if (offset)
1538 *offset = 0;
1539 return;
1540 }
1541
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001542 const SourceManager &SM =
1543 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001544 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001545
1546 if (file)
1547 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1548 if (line)
1549 *line = SM.getInstantiationLineNumber(InstLoc);
1550 if (column)
1551 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001552 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001553 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001554}
1555
Douglas Gregor1db19de2010-01-19 21:36:55 +00001556CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001557 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001558 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001559 return Result;
1560}
1561
1562CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001563 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001564 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001565 return Result;
1566}
1567
Douglas Gregorb9790342010-01-22 21:44:22 +00001568} // end: extern "C"
1569
Douglas Gregor1db19de2010-01-19 21:36:55 +00001570//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001571// CXFile Operations.
1572//===----------------------------------------------------------------------===//
1573
1574extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001575CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001576 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001577 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001578
Steve Naroff88145032009-10-27 14:35:18 +00001579 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001580 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001581}
1582
1583time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001584 if (!SFile)
1585 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001586
Steve Naroff88145032009-10-27 14:35:18 +00001587 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1588 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001589}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001590
Douglas Gregorb9790342010-01-22 21:44:22 +00001591CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1592 if (!tu)
1593 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001594
Douglas Gregorb9790342010-01-22 21:44:22 +00001595 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001596
Douglas Gregorb9790342010-01-22 21:44:22 +00001597 FileManager &FMgr = CXXUnit->getFileManager();
1598 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1599 return const_cast<FileEntry *>(File);
1600}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001601
Ted Kremenekfb480492010-01-13 21:46:36 +00001602} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001603
Ted Kremenekfb480492010-01-13 21:46:36 +00001604//===----------------------------------------------------------------------===//
1605// CXCursor Operations.
1606//===----------------------------------------------------------------------===//
1607
Ted Kremenekfb480492010-01-13 21:46:36 +00001608static Decl *getDeclFromExpr(Stmt *E) {
1609 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1610 return RefExpr->getDecl();
1611 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1612 return ME->getMemberDecl();
1613 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1614 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001615
Ted Kremenekfb480492010-01-13 21:46:36 +00001616 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1617 return getDeclFromExpr(CE->getCallee());
1618 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1619 return getDeclFromExpr(CE->getSubExpr());
1620 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1621 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001622
Ted Kremenekfb480492010-01-13 21:46:36 +00001623 return 0;
1624}
1625
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001626static SourceLocation getLocationFromExpr(Expr *E) {
1627 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1628 return /*FIXME:*/Msg->getLeftLoc();
1629 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1630 return DRE->getLocation();
1631 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1632 return Member->getMemberLoc();
1633 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1634 return Ivar->getLocation();
1635 return E->getLocStart();
1636}
1637
Ted Kremenekfb480492010-01-13 21:46:36 +00001638extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001639
1640unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001641 CXCursorVisitor visitor,
1642 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001643 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001644
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001645 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1646 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00001647 return CursorVis.VisitChildren(parent);
1648}
1649
Douglas Gregor78205d42010-01-20 21:45:58 +00001650static CXString getDeclSpelling(Decl *D) {
1651 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1652 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001653 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001654
Douglas Gregor78205d42010-01-20 21:45:58 +00001655 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001656 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001657
Douglas Gregor78205d42010-01-20 21:45:58 +00001658 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1659 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1660 // and returns different names. NamedDecl returns the class name and
1661 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001662 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001663
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001664 llvm::SmallString<1024> S;
1665 llvm::raw_svector_ostream os(S);
1666 ND->printName(os);
1667
1668 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001669}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001670
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001671CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001672 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001673 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001674
Steve Narofff334b4e2009-09-02 18:26:48 +00001675 if (clang_isReference(C.kind)) {
1676 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001677 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001678 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001679 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001680 }
1681 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001682 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001683 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001684 }
1685 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001686 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001687 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001688 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001689 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001690 case CXCursor_TypeRef: {
1691 TypeDecl *Type = getCursorTypeRef(C).first;
1692 assert(Type && "Missing type decl");
1693
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001694 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1695 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001696 }
1697
Daniel Dunbaracca7252009-11-30 20:42:49 +00001698 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001699 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001700 }
1701 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001702
1703 if (clang_isExpression(C.kind)) {
1704 Decl *D = getDeclFromExpr(getCursorExpr(C));
1705 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001706 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001707 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001708 }
1709
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001710 if (C.kind == CXCursor_MacroInstantiation)
1711 return createCXString(getCursorMacroInstantiation(C)->getName()
1712 ->getNameStart());
1713
Douglas Gregor572feb22010-03-18 18:04:21 +00001714 if (C.kind == CXCursor_MacroDefinition)
1715 return createCXString(getCursorMacroDefinition(C)->getName()
1716 ->getNameStart());
1717
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001718 if (clang_isDeclaration(C.kind))
1719 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001720
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001721 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001722}
1723
Ted Kremeneke68fff62010-02-17 00:41:32 +00001724CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001725 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001726 case CXCursor_FunctionDecl:
1727 return createCXString("FunctionDecl");
1728 case CXCursor_TypedefDecl:
1729 return createCXString("TypedefDecl");
1730 case CXCursor_EnumDecl:
1731 return createCXString("EnumDecl");
1732 case CXCursor_EnumConstantDecl:
1733 return createCXString("EnumConstantDecl");
1734 case CXCursor_StructDecl:
1735 return createCXString("StructDecl");
1736 case CXCursor_UnionDecl:
1737 return createCXString("UnionDecl");
1738 case CXCursor_ClassDecl:
1739 return createCXString("ClassDecl");
1740 case CXCursor_FieldDecl:
1741 return createCXString("FieldDecl");
1742 case CXCursor_VarDecl:
1743 return createCXString("VarDecl");
1744 case CXCursor_ParmDecl:
1745 return createCXString("ParmDecl");
1746 case CXCursor_ObjCInterfaceDecl:
1747 return createCXString("ObjCInterfaceDecl");
1748 case CXCursor_ObjCCategoryDecl:
1749 return createCXString("ObjCCategoryDecl");
1750 case CXCursor_ObjCProtocolDecl:
1751 return createCXString("ObjCProtocolDecl");
1752 case CXCursor_ObjCPropertyDecl:
1753 return createCXString("ObjCPropertyDecl");
1754 case CXCursor_ObjCIvarDecl:
1755 return createCXString("ObjCIvarDecl");
1756 case CXCursor_ObjCInstanceMethodDecl:
1757 return createCXString("ObjCInstanceMethodDecl");
1758 case CXCursor_ObjCClassMethodDecl:
1759 return createCXString("ObjCClassMethodDecl");
1760 case CXCursor_ObjCImplementationDecl:
1761 return createCXString("ObjCImplementationDecl");
1762 case CXCursor_ObjCCategoryImplDecl:
1763 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001764 case CXCursor_CXXMethod:
1765 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001766 case CXCursor_UnexposedDecl:
1767 return createCXString("UnexposedDecl");
1768 case CXCursor_ObjCSuperClassRef:
1769 return createCXString("ObjCSuperClassRef");
1770 case CXCursor_ObjCProtocolRef:
1771 return createCXString("ObjCProtocolRef");
1772 case CXCursor_ObjCClassRef:
1773 return createCXString("ObjCClassRef");
1774 case CXCursor_TypeRef:
1775 return createCXString("TypeRef");
1776 case CXCursor_UnexposedExpr:
1777 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001778 case CXCursor_BlockExpr:
1779 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001780 case CXCursor_DeclRefExpr:
1781 return createCXString("DeclRefExpr");
1782 case CXCursor_MemberRefExpr:
1783 return createCXString("MemberRefExpr");
1784 case CXCursor_CallExpr:
1785 return createCXString("CallExpr");
1786 case CXCursor_ObjCMessageExpr:
1787 return createCXString("ObjCMessageExpr");
1788 case CXCursor_UnexposedStmt:
1789 return createCXString("UnexposedStmt");
1790 case CXCursor_InvalidFile:
1791 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001792 case CXCursor_InvalidCode:
1793 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001794 case CXCursor_NoDeclFound:
1795 return createCXString("NoDeclFound");
1796 case CXCursor_NotImplemented:
1797 return createCXString("NotImplemented");
1798 case CXCursor_TranslationUnit:
1799 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001800 case CXCursor_UnexposedAttr:
1801 return createCXString("UnexposedAttr");
1802 case CXCursor_IBActionAttr:
1803 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001804 case CXCursor_IBOutletAttr:
1805 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00001806 case CXCursor_IBOutletCollectionAttr:
1807 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001808 case CXCursor_PreprocessingDirective:
1809 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001810 case CXCursor_MacroDefinition:
1811 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001812 case CXCursor_MacroInstantiation:
1813 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001814 case CXCursor_Namespace:
1815 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001816 case CXCursor_LinkageSpec:
1817 return createCXString("LinkageSpec");
Steve Naroff89922f82009-08-31 00:59:03 +00001818 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001819
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001820 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001821 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001822}
Steve Naroff89922f82009-08-31 00:59:03 +00001823
Ted Kremeneke68fff62010-02-17 00:41:32 +00001824enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1825 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001826 CXClientData client_data) {
1827 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1828 *BestCursor = cursor;
1829 return CXChildVisit_Recurse;
1830}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001831
Douglas Gregorb9790342010-01-22 21:44:22 +00001832CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1833 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001834 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001835
Douglas Gregorb9790342010-01-22 21:44:22 +00001836 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00001837 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1838
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001839 // Translate the given source location to make it point at the beginning of
1840 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00001841 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00001842
1843 // Guard against an invalid SourceLocation, or we may assert in one
1844 // of the following calls.
1845 if (SLoc.isInvalid())
1846 return clang_getNullCursor();
1847
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001848 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
1849 CXXUnit->getASTContext().getLangOptions());
1850
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001851 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1852 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001853 // FIXME: Would be great to have a "hint" cursor, then walk from that
1854 // hint cursor upward until we find a cursor whose source range encloses
1855 // the region of interest, rather than starting from the translation unit.
1856 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001857 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001858 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001859 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001860 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001861 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001862}
1863
Ted Kremenek73885552009-11-17 19:28:59 +00001864CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001865 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001866}
1867
1868unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001869 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001870}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001871
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001872unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001873 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1874}
1875
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001876unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001877 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1878}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001879
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001880unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001881 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1882}
1883
Douglas Gregor97b98722010-01-19 23:20:36 +00001884unsigned clang_isExpression(enum CXCursorKind K) {
1885 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1886}
1887
1888unsigned clang_isStatement(enum CXCursorKind K) {
1889 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1890}
1891
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001892unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1893 return K == CXCursor_TranslationUnit;
1894}
1895
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001896unsigned clang_isPreprocessing(enum CXCursorKind K) {
1897 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1898}
1899
Ted Kremenekad6eff62010-03-08 21:17:29 +00001900unsigned clang_isUnexposed(enum CXCursorKind K) {
1901 switch (K) {
1902 case CXCursor_UnexposedDecl:
1903 case CXCursor_UnexposedExpr:
1904 case CXCursor_UnexposedStmt:
1905 case CXCursor_UnexposedAttr:
1906 return true;
1907 default:
1908 return false;
1909 }
1910}
1911
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001912CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001913 return C.kind;
1914}
1915
Douglas Gregor98258af2010-01-18 22:46:11 +00001916CXSourceLocation clang_getCursorLocation(CXCursor C) {
1917 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001918 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001919 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001920 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1921 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001922 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001923 }
1924
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001925 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001926 std::pair<ObjCProtocolDecl *, SourceLocation> P
1927 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001928 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001929 }
1930
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001931 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001932 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1933 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001934 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001935 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001936
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001937 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001938 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001939 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001940 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001941
Douglas Gregorf46034a2010-01-18 23:41:10 +00001942 default:
1943 // FIXME: Need a way to enumerate all non-reference cases.
1944 llvm_unreachable("Missed a reference kind");
1945 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001946 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001947
1948 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001949 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001950 getLocationFromExpr(getCursorExpr(C)));
1951
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001952 if (C.kind == CXCursor_PreprocessingDirective) {
1953 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1954 return cxloc::translateSourceLocation(getCursorContext(C), L);
1955 }
Douglas Gregor48072312010-03-18 15:23:44 +00001956
1957 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001958 SourceLocation L
1959 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001960 return cxloc::translateSourceLocation(getCursorContext(C), L);
1961 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001962
1963 if (C.kind == CXCursor_MacroDefinition) {
1964 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1965 return cxloc::translateSourceLocation(getCursorContext(C), L);
1966 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001967
Ted Kremenek9a700d22010-05-12 06:16:13 +00001968 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00001969 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001970
Douglas Gregorf46034a2010-01-18 23:41:10 +00001971 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001972 SourceLocation Loc = D->getLocation();
1973 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1974 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001975 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001976}
Douglas Gregora7bde202010-01-19 00:34:46 +00001977
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001978} // end extern "C"
1979
1980static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00001981 if (clang_isReference(C.kind)) {
1982 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001983 case CXCursor_ObjCSuperClassRef:
1984 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001985
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001986 case CXCursor_ObjCProtocolRef:
1987 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001988
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001989 case CXCursor_ObjCClassRef:
1990 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001991
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001992 case CXCursor_TypeRef:
1993 return getCursorTypeRef(C).second;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001994
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001995 default:
1996 // FIXME: Need a way to enumerate all non-reference cases.
1997 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00001998 }
1999 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002000
2001 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002002 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002003
2004 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002005 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002006
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002007 if (C.kind == CXCursor_PreprocessingDirective)
2008 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002009
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002010 if (C.kind == CXCursor_MacroInstantiation)
2011 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002012
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002013 if (C.kind == CXCursor_MacroDefinition)
2014 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002015
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002016 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2017 return getCursorDecl(C)->getSourceRange();
2018
2019 return SourceRange();
2020}
2021
2022extern "C" {
2023
2024CXSourceRange clang_getCursorExtent(CXCursor C) {
2025 SourceRange R = getRawCursorExtent(C);
2026 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002027 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002028
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002029 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002030}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002031
2032CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002033 if (clang_isInvalid(C.kind))
2034 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002035
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002036 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002037 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002038 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002039
Douglas Gregor97b98722010-01-19 23:20:36 +00002040 if (clang_isExpression(C.kind)) {
2041 Decl *D = getDeclFromExpr(getCursorExpr(C));
2042 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002043 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002044 return clang_getNullCursor();
2045 }
2046
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002047 if (C.kind == CXCursor_MacroInstantiation) {
2048 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2049 return MakeMacroDefinitionCursor(Def, CXXUnit);
2050 }
2051
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002052 if (!clang_isReference(C.kind))
2053 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002054
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002055 switch (C.kind) {
2056 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002057 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002058
2059 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002060 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002061
2062 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002063 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002064
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002065 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002066 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002067
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002068 default:
2069 // We would prefer to enumerate all non-reference cursor kinds here.
2070 llvm_unreachable("Unhandled reference cursor kind");
2071 break;
2072 }
2073 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002074
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002075 return clang_getNullCursor();
2076}
2077
Douglas Gregorb6998662010-01-19 19:34:47 +00002078CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002079 if (clang_isInvalid(C.kind))
2080 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002081
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002082 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002083
Douglas Gregorb6998662010-01-19 19:34:47 +00002084 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002085 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002086 C = clang_getCursorReferenced(C);
2087 WasReference = true;
2088 }
2089
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002090 if (C.kind == CXCursor_MacroInstantiation)
2091 return clang_getCursorReferenced(C);
2092
Douglas Gregorb6998662010-01-19 19:34:47 +00002093 if (!clang_isDeclaration(C.kind))
2094 return clang_getNullCursor();
2095
2096 Decl *D = getCursorDecl(C);
2097 if (!D)
2098 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002099
Douglas Gregorb6998662010-01-19 19:34:47 +00002100 switch (D->getKind()) {
2101 // Declaration kinds that don't really separate the notions of
2102 // declaration and definition.
2103 case Decl::Namespace:
2104 case Decl::Typedef:
2105 case Decl::TemplateTypeParm:
2106 case Decl::EnumConstant:
2107 case Decl::Field:
2108 case Decl::ObjCIvar:
2109 case Decl::ObjCAtDefsField:
2110 case Decl::ImplicitParam:
2111 case Decl::ParmVar:
2112 case Decl::NonTypeTemplateParm:
2113 case Decl::TemplateTemplateParm:
2114 case Decl::ObjCCategoryImpl:
2115 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002116 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002117 case Decl::LinkageSpec:
2118 case Decl::ObjCPropertyImpl:
2119 case Decl::FileScopeAsm:
2120 case Decl::StaticAssert:
2121 case Decl::Block:
2122 return C;
2123
2124 // Declaration kinds that don't make any sense here, but are
2125 // nonetheless harmless.
2126 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002127 break;
2128
2129 // Declaration kinds for which the definition is not resolvable.
2130 case Decl::UnresolvedUsingTypename:
2131 case Decl::UnresolvedUsingValue:
2132 break;
2133
2134 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002135 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2136 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002137
2138 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002139 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002140
2141 case Decl::Enum:
2142 case Decl::Record:
2143 case Decl::CXXRecord:
2144 case Decl::ClassTemplateSpecialization:
2145 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002146 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002147 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002148 return clang_getNullCursor();
2149
2150 case Decl::Function:
2151 case Decl::CXXMethod:
2152 case Decl::CXXConstructor:
2153 case Decl::CXXDestructor:
2154 case Decl::CXXConversion: {
2155 const FunctionDecl *Def = 0;
2156 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002157 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002158 return clang_getNullCursor();
2159 }
2160
2161 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002162 // Ask the variable if it has a definition.
2163 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2164 return MakeCXCursor(Def, CXXUnit);
2165 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002166 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002167
Douglas Gregorb6998662010-01-19 19:34:47 +00002168 case Decl::FunctionTemplate: {
2169 const FunctionDecl *Def = 0;
2170 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002171 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002172 return clang_getNullCursor();
2173 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002174
Douglas Gregorb6998662010-01-19 19:34:47 +00002175 case Decl::ClassTemplate: {
2176 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002177 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002178 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002179 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002180 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002181 return clang_getNullCursor();
2182 }
2183
2184 case Decl::Using: {
2185 UsingDecl *Using = cast<UsingDecl>(D);
2186 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002187 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2188 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002189 S != SEnd; ++S) {
2190 if (Def != clang_getNullCursor()) {
2191 // FIXME: We have no way to return multiple results.
2192 return clang_getNullCursor();
2193 }
2194
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002195 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002196 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002197 }
2198
2199 return Def;
2200 }
2201
2202 case Decl::UsingShadow:
2203 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002204 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002205 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002206
2207 case Decl::ObjCMethod: {
2208 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2209 if (Method->isThisDeclarationADefinition())
2210 return C;
2211
2212 // Dig out the method definition in the associated
2213 // @implementation, if we have it.
2214 // FIXME: The ASTs should make finding the definition easier.
2215 if (ObjCInterfaceDecl *Class
2216 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2217 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2218 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2219 Method->isInstanceMethod()))
2220 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002221 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002222
2223 return clang_getNullCursor();
2224 }
2225
2226 case Decl::ObjCCategory:
2227 if (ObjCCategoryImplDecl *Impl
2228 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002229 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002230 return clang_getNullCursor();
2231
2232 case Decl::ObjCProtocol:
2233 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2234 return C;
2235 return clang_getNullCursor();
2236
2237 case Decl::ObjCInterface:
2238 // There are two notions of a "definition" for an Objective-C
2239 // class: the interface and its implementation. When we resolved a
2240 // reference to an Objective-C class, produce the @interface as
2241 // the definition; when we were provided with the interface,
2242 // produce the @implementation as the definition.
2243 if (WasReference) {
2244 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2245 return C;
2246 } else if (ObjCImplementationDecl *Impl
2247 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002248 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002249 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002250
Douglas Gregorb6998662010-01-19 19:34:47 +00002251 case Decl::ObjCProperty:
2252 // FIXME: We don't really know where to find the
2253 // ObjCPropertyImplDecls that implement this property.
2254 return clang_getNullCursor();
2255
2256 case Decl::ObjCCompatibleAlias:
2257 if (ObjCInterfaceDecl *Class
2258 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2259 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002260 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002261
Douglas Gregorb6998662010-01-19 19:34:47 +00002262 return clang_getNullCursor();
2263
2264 case Decl::ObjCForwardProtocol: {
2265 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2266 if (Forward->protocol_size() == 1)
2267 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002268 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002269 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002270
2271 // FIXME: Cannot return multiple definitions.
2272 return clang_getNullCursor();
2273 }
2274
2275 case Decl::ObjCClass: {
2276 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2277 if (Class->size() == 1) {
2278 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2279 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002280 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002281 return clang_getNullCursor();
2282 }
2283
2284 // FIXME: Cannot return multiple definitions.
2285 return clang_getNullCursor();
2286 }
2287
2288 case Decl::Friend:
2289 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002290 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002291 return clang_getNullCursor();
2292
2293 case Decl::FriendTemplate:
2294 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002295 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002296 return clang_getNullCursor();
2297 }
2298
2299 return clang_getNullCursor();
2300}
2301
2302unsigned clang_isCursorDefinition(CXCursor C) {
2303 if (!clang_isDeclaration(C.kind))
2304 return 0;
2305
2306 return clang_getCursorDefinition(C) == C;
2307}
2308
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002309void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002310 const char **startBuf,
2311 const char **endBuf,
2312 unsigned *startLine,
2313 unsigned *startColumn,
2314 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002315 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002316 assert(getCursorDecl(C) && "CXCursor has null decl");
2317 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002318 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2319 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002320
Steve Naroff4ade6d62009-09-23 17:52:52 +00002321 SourceManager &SM = FD->getASTContext().getSourceManager();
2322 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2323 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2324 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2325 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2326 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2327 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2328}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002329
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002330void clang_enableStackTraces(void) {
2331 llvm::sys::PrintStackTraceOnErrorSignal();
2332}
2333
Ted Kremenekfb480492010-01-13 21:46:36 +00002334} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002335
Ted Kremenekfb480492010-01-13 21:46:36 +00002336//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002337// Token-based Operations.
2338//===----------------------------------------------------------------------===//
2339
2340/* CXToken layout:
2341 * int_data[0]: a CXTokenKind
2342 * int_data[1]: starting token location
2343 * int_data[2]: token length
2344 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002345 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002346 * otherwise unused.
2347 */
2348extern "C" {
2349
2350CXTokenKind clang_getTokenKind(CXToken CXTok) {
2351 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2352}
2353
2354CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2355 switch (clang_getTokenKind(CXTok)) {
2356 case CXToken_Identifier:
2357 case CXToken_Keyword:
2358 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002359 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2360 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002361
2362 case CXToken_Literal: {
2363 // We have stashed the starting pointer in the ptr_data field. Use it.
2364 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002365 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002366 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002367
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002368 case CXToken_Punctuation:
2369 case CXToken_Comment:
2370 break;
2371 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002372
2373 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002374 // deconstructing the source location.
2375 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2376 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002377 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002378
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002379 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2380 std::pair<FileID, unsigned> LocInfo
2381 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002382 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002383 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002384 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2385 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002386 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002387
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002388 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002389}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002390
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002391CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2392 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2393 if (!CXXUnit)
2394 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002395
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002396 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2397 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2398}
2399
2400CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2401 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002402 if (!CXXUnit)
2403 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002404
2405 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002406 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2407}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002408
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002409void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2410 CXToken **Tokens, unsigned *NumTokens) {
2411 if (Tokens)
2412 *Tokens = 0;
2413 if (NumTokens)
2414 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002415
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002416 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2417 if (!CXXUnit || !Tokens || !NumTokens)
2418 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002419
Douglas Gregorbdf60622010-03-05 21:16:25 +00002420 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2421
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002422 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002423 if (R.isInvalid())
2424 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002425
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002426 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2427 std::pair<FileID, unsigned> BeginLocInfo
2428 = SourceMgr.getDecomposedLoc(R.getBegin());
2429 std::pair<FileID, unsigned> EndLocInfo
2430 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002431
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002432 // Cannot tokenize across files.
2433 if (BeginLocInfo.first != EndLocInfo.first)
2434 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002435
2436 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002437 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002438 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002439 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002440 if (Invalid)
2441 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002442
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002443 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2444 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002445 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002446 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002447
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002448 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002449 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002450 llvm::SmallVector<CXToken, 32> CXTokens;
2451 Token Tok;
2452 do {
2453 // Lex the next token
2454 Lex.LexFromRawLexer(Tok);
2455 if (Tok.is(tok::eof))
2456 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002457
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002458 // Initialize the CXToken.
2459 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002460
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002461 // - Common fields
2462 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2463 CXTok.int_data[2] = Tok.getLength();
2464 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002465
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002466 // - Kind-specific fields
2467 if (Tok.isLiteral()) {
2468 CXTok.int_data[0] = CXToken_Literal;
2469 CXTok.ptr_data = (void *)Tok.getLiteralData();
2470 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002471 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002472 std::pair<FileID, unsigned> LocInfo
2473 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002474 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002475 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002476 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2477 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002478 return;
2479
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002480 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002481 IdentifierInfo *II
2482 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002483
2484 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2485 CXTok.int_data[0] = CXToken_Keyword;
2486 }
2487 else {
2488 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2489 CXToken_Identifier
2490 : CXToken_Keyword;
2491 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002492 CXTok.ptr_data = II;
2493 } else if (Tok.is(tok::comment)) {
2494 CXTok.int_data[0] = CXToken_Comment;
2495 CXTok.ptr_data = 0;
2496 } else {
2497 CXTok.int_data[0] = CXToken_Punctuation;
2498 CXTok.ptr_data = 0;
2499 }
2500 CXTokens.push_back(CXTok);
2501 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002502
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002503 if (CXTokens.empty())
2504 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002505
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002506 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2507 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2508 *NumTokens = CXTokens.size();
2509}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002510
Ted Kremenek6db61092010-05-05 00:55:15 +00002511void clang_disposeTokens(CXTranslationUnit TU,
2512 CXToken *Tokens, unsigned NumTokens) {
2513 free(Tokens);
2514}
2515
2516} // end: extern "C"
2517
2518//===----------------------------------------------------------------------===//
2519// Token annotation APIs.
2520//===----------------------------------------------------------------------===//
2521
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002522typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002523static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2524 CXCursor parent,
2525 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002526namespace {
2527class AnnotateTokensWorker {
2528 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002529 CXToken *Tokens;
2530 CXCursor *Cursors;
2531 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002532 unsigned TokIdx;
2533 CursorVisitor AnnotateVis;
2534 SourceManager &SrcMgr;
2535
2536 bool MoreTokens() const { return TokIdx < NumTokens; }
2537 unsigned NextToken() const { return TokIdx; }
2538 void AdvanceToken() { ++TokIdx; }
2539 SourceLocation GetTokenLoc(unsigned tokI) {
2540 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2541 }
2542
Ted Kremenek6db61092010-05-05 00:55:15 +00002543public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002544 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002545 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2546 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002547 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002548 NumTokens(numTokens), TokIdx(0),
2549 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2550 Decl::MaxPCHLevel, RegionOfInterest),
2551 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002552
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002553 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002554 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002555 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002556};
2557}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002558
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002559void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2560 // Walk the AST within the region of interest, annotating tokens
2561 // along the way.
2562 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002563
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002564 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2565 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2566 if (Pos != Annotated.end())
2567 Cursors[I] = Pos->second;
2568 }
2569
2570 // Finish up annotating any tokens left.
2571 if (!MoreTokens())
2572 return;
2573
2574 const CXCursor &C = clang_getNullCursor();
2575 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2576 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2577 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002578 }
2579}
2580
Ted Kremenek6db61092010-05-05 00:55:15 +00002581enum CXChildVisitResult
2582AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002583 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2584 // We can always annotate a preprocessing directive/macro instantiation.
2585 if (clang_isPreprocessing(cursor.kind)) {
2586 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002587 return CXChildVisit_Recurse;
2588 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002589
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002590 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00002591
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002592 if (cursorRange.isInvalid())
2593 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002594
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002595 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2596
Ted Kremeneka333c662010-05-12 05:29:33 +00002597 // Adjust the annotated range based specific declarations.
2598 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2599 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002600 Decl *D = cxcursor::getCursorDecl(cursor);
2601 // Don't visit synthesized ObjC methods, since they have no syntatic
2602 // representation in the source.
2603 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2604 if (MD->isSynthesized())
2605 return CXChildVisit_Continue;
2606 }
2607 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002608 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2609 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002610 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002611 if (TLoc.isValid() &&
2612 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002613 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002614 }
2615 }
2616 }
2617
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002618 const enum CXCursorKind K = clang_getCursorKind(parent);
2619 const CXCursor updateC =
2620 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2621 L.isMacroID())
2622 ? clang_getNullCursor() : parent;
2623
2624 while (MoreTokens()) {
2625 const unsigned I = NextToken();
2626 SourceLocation TokLoc = GetTokenLoc(I);
2627 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2628 case RangeBefore:
2629 Cursors[I] = updateC;
2630 AdvanceToken();
2631 continue;
2632 case RangeAfter:
2633 return CXChildVisit_Continue;
2634 case RangeOverlap:
2635 break;
2636 }
2637 break;
2638 }
2639
2640 // Visit children to get their cursor information.
2641 const unsigned BeforeChildren = NextToken();
2642 VisitChildren(cursor);
2643 const unsigned AfterChildren = NextToken();
2644
2645 // Adjust 'Last' to the last token within the extent of the cursor.
2646 while (MoreTokens()) {
2647 const unsigned I = NextToken();
2648 SourceLocation TokLoc = GetTokenLoc(I);
2649 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2650 case RangeBefore:
2651 assert(0 && "Infeasible");
2652 case RangeAfter:
2653 break;
2654 case RangeOverlap:
2655 Cursors[I] = updateC;
2656 AdvanceToken();
2657 continue;
2658 }
2659 break;
2660 }
2661 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002662
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002663 // Scan the tokens that are at the beginning of the cursor, but are not
2664 // capture by the child cursors.
2665
2666 // For AST elements within macros, rely on a post-annotate pass to
2667 // to correctly annotate the tokens with cursors. Otherwise we can
2668 // get confusing results of having tokens that map to cursors that really
2669 // are expanded by an instantiation.
2670 if (L.isMacroID())
2671 cursor = clang_getNullCursor();
2672
2673 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2674 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2675 break;
2676 Cursors[I] = cursor;
2677 }
2678 // Scan the tokens that are at the end of the cursor, but are not captured
2679 // but the child cursors.
2680 for (unsigned I = AfterChildren; I != Last; ++I)
2681 Cursors[I] = cursor;
2682
2683 TokIdx = Last;
2684 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002685}
2686
Ted Kremenek6db61092010-05-05 00:55:15 +00002687static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2688 CXCursor parent,
2689 CXClientData client_data) {
2690 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2691}
2692
2693extern "C" {
2694
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002695void clang_annotateTokens(CXTranslationUnit TU,
2696 CXToken *Tokens, unsigned NumTokens,
2697 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002698
2699 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002700 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002701
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002702 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002703 if (!CXXUnit) {
2704 // Any token we don't specifically annotate will have a NULL cursor.
2705 const CXCursor &C = clang_getNullCursor();
2706 for (unsigned I = 0; I != NumTokens; ++I)
2707 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002708 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002709 }
2710
Douglas Gregorbdf60622010-03-05 21:16:25 +00002711 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002712
Douglas Gregor0396f462010-03-19 05:22:59 +00002713 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002714 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002715 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2716 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002717 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
2718 clang_getTokenLocation(TU,
2719 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002720
Douglas Gregor0396f462010-03-19 05:22:59 +00002721 // A mapping from the source locations found when re-lexing or traversing the
2722 // region of interest to the corresponding cursors.
2723 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002724
2725 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002726 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002727 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2728 std::pair<FileID, unsigned> BeginLocInfo
2729 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2730 std::pair<FileID, unsigned> EndLocInfo
2731 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002732
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002733 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002734 bool Invalid = false;
2735 if (BeginLocInfo.first == EndLocInfo.first &&
2736 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2737 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002738 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2739 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002740 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002741 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002742 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002743
2744 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002745 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002746 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002747 Token Tok;
2748 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002749
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002750 reprocess:
2751 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2752 // We have found a preprocessing directive. Gobble it up so that we
2753 // don't see it while preprocessing these tokens later, but keep track of
2754 // all of the token locations inside this preprocessing directive so that
2755 // we can annotate them appropriately.
2756 //
2757 // FIXME: Some simple tests here could identify macro definitions and
2758 // #undefs, to provide specific cursor kinds for those.
2759 std::vector<SourceLocation> Locations;
2760 do {
2761 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002762 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002763 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002764
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002765 using namespace cxcursor;
2766 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002767 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2768 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002769 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002770 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2771 Annotated[Locations[I].getRawEncoding()] = Cursor;
2772 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002773
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002774 if (Tok.isAtStartOfLine())
2775 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002776
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002777 continue;
2778 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002779
Douglas Gregor48072312010-03-18 15:23:44 +00002780 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002781 break;
2782 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002783 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002784
Douglas Gregor0396f462010-03-19 05:22:59 +00002785 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002786 // a specific cursor.
2787 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2788 CXXUnit, RegionOfInterest);
2789 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002790}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002791} // end: extern "C"
2792
2793//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002794// Operations for querying linkage of a cursor.
2795//===----------------------------------------------------------------------===//
2796
2797extern "C" {
2798CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002799 if (!clang_isDeclaration(cursor.kind))
2800 return CXLinkage_Invalid;
2801
Ted Kremenek16b42592010-03-03 06:36:57 +00002802 Decl *D = cxcursor::getCursorDecl(cursor);
2803 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2804 switch (ND->getLinkage()) {
2805 case NoLinkage: return CXLinkage_NoLinkage;
2806 case InternalLinkage: return CXLinkage_Internal;
2807 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2808 case ExternalLinkage: return CXLinkage_External;
2809 };
2810
2811 return CXLinkage_Invalid;
2812}
2813} // end: extern "C"
2814
2815//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002816// Operations for querying language of a cursor.
2817//===----------------------------------------------------------------------===//
2818
2819static CXLanguageKind getDeclLanguage(const Decl *D) {
2820 switch (D->getKind()) {
2821 default:
2822 break;
2823 case Decl::ImplicitParam:
2824 case Decl::ObjCAtDefsField:
2825 case Decl::ObjCCategory:
2826 case Decl::ObjCCategoryImpl:
2827 case Decl::ObjCClass:
2828 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002829 case Decl::ObjCForwardProtocol:
2830 case Decl::ObjCImplementation:
2831 case Decl::ObjCInterface:
2832 case Decl::ObjCIvar:
2833 case Decl::ObjCMethod:
2834 case Decl::ObjCProperty:
2835 case Decl::ObjCPropertyImpl:
2836 case Decl::ObjCProtocol:
2837 return CXLanguage_ObjC;
2838 case Decl::CXXConstructor:
2839 case Decl::CXXConversion:
2840 case Decl::CXXDestructor:
2841 case Decl::CXXMethod:
2842 case Decl::CXXRecord:
2843 case Decl::ClassTemplate:
2844 case Decl::ClassTemplatePartialSpecialization:
2845 case Decl::ClassTemplateSpecialization:
2846 case Decl::Friend:
2847 case Decl::FriendTemplate:
2848 case Decl::FunctionTemplate:
2849 case Decl::LinkageSpec:
2850 case Decl::Namespace:
2851 case Decl::NamespaceAlias:
2852 case Decl::NonTypeTemplateParm:
2853 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002854 case Decl::TemplateTemplateParm:
2855 case Decl::TemplateTypeParm:
2856 case Decl::UnresolvedUsingTypename:
2857 case Decl::UnresolvedUsingValue:
2858 case Decl::Using:
2859 case Decl::UsingDirective:
2860 case Decl::UsingShadow:
2861 return CXLanguage_CPlusPlus;
2862 }
2863
2864 return CXLanguage_C;
2865}
2866
2867extern "C" {
2868CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2869 if (clang_isDeclaration(cursor.kind))
2870 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2871
2872 return CXLanguage_Invalid;
2873}
2874} // end: extern "C"
2875
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002876
2877//===----------------------------------------------------------------------===//
2878// C++ AST instrospection.
2879//===----------------------------------------------------------------------===//
2880
2881extern "C" {
2882unsigned clang_CXXMethod_isStatic(CXCursor C) {
2883 if (!clang_isDeclaration(C.kind))
2884 return 0;
2885 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
2886 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00002887}
Ted Kremenekb12903e2010-05-18 22:32:15 +00002888
Ted Kremenek9ada39a2010-05-17 20:06:56 +00002889} // end: extern "C"
2890
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002891//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002892// CXString Operations.
2893//===----------------------------------------------------------------------===//
2894
2895extern "C" {
2896const char *clang_getCString(CXString string) {
2897 return string.Spelling;
2898}
2899
2900void clang_disposeString(CXString string) {
2901 if (string.MustFreeString && string.Spelling)
2902 free((void*)string.Spelling);
2903}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002904
Ted Kremenekfb480492010-01-13 21:46:36 +00002905} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002906
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002907namespace clang { namespace cxstring {
2908CXString createCXString(const char *String, bool DupString){
2909 CXString Str;
2910 if (DupString) {
2911 Str.Spelling = strdup(String);
2912 Str.MustFreeString = 1;
2913 } else {
2914 Str.Spelling = String;
2915 Str.MustFreeString = 0;
2916 }
2917 return Str;
2918}
2919
2920CXString createCXString(llvm::StringRef String, bool DupString) {
2921 CXString Result;
2922 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2923 char *Spelling = (char *)malloc(String.size() + 1);
2924 memmove(Spelling, String.data(), String.size());
2925 Spelling[String.size()] = 0;
2926 Result.Spelling = Spelling;
2927 Result.MustFreeString = 1;
2928 } else {
2929 Result.Spelling = String.data();
2930 Result.MustFreeString = 0;
2931 }
2932 return Result;
2933}
2934}}
2935
Ted Kremenek04bb7162010-01-22 22:44:15 +00002936//===----------------------------------------------------------------------===//
2937// Misc. utility functions.
2938//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002939
Ted Kremenek04bb7162010-01-22 22:44:15 +00002940extern "C" {
2941
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002942CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002943 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002944}
2945
2946} // end: extern "C"