blob: 4ec2bf4c291bb32ebac7a9dfb0c9ba2f35c6fdaa [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 Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000033#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor02465752009-10-16 21:24:31 +000034#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000035#include "llvm/Support/Timer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000036#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000037#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000038
Benjamin Kramerc2a98162010-03-13 21:22:49 +000039// Needed to define L_TMPNAM on some systems.
40#include <cstdio>
41
Steve Naroff50398192009-08-28 15:28:48 +000042using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000043using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000044using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000045
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000046//===----------------------------------------------------------------------===//
47// Crash Reporting.
48//===----------------------------------------------------------------------===//
49
Ted Kremenekd7ffd082010-05-22 00:06:46 +000050#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000051#include "clang/Analysis/Support/SaveAndRestore.h"
52// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000053static const char *__crashreporter_info__ = 0;
54asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000055#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000056static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000057static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000058static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
59static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
60
61static unsigned SetCrashTracerInfo(const char *str,
62 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000063
Ted Kremenek254ba7c2010-01-07 23:13:53 +000064 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000065 while (crashtracer_strings[slot]) {
66 if (++slot == NUM_CRASH_STRINGS)
67 slot = 0;
68 }
69 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000070 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000071
72 // We need to create an aggregate string because multiple threads
73 // may be in this method at one time. The crash reporter string
74 // will attempt to overapproximate the set of in-flight invocations
75 // of this function. Race conditions can still cause this goal
76 // to not be achieved.
77 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000078 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000079 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
80 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
81 }
82 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
83 return slot;
84}
85
86static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000087 unsigned max_slot = 0;
88 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000089
Ted Kremenek254ba7c2010-01-07 23:13:53 +000090 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
91
92 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
93 if (agg_crashtracer_strings[i] &&
94 crashtracer_counter_id[i] > max_value) {
95 max_slot = i;
96 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000097 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000098
99 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +0000100}
101
102namespace {
103class ArgsCrashTracerInfo {
104 llvm::SmallString<1024> CrashString;
105 llvm::SmallString<1024> AggregateString;
106 unsigned crashtracerSlot;
107public:
108 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
109 : crashtracerSlot(0)
110 {
111 {
112 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000113 Out << "ClangCIndex [" << getClangFullVersion() << "]"
114 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000115 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
116 E=Args.end(); I!=E; ++I)
117 Out << ' ' << *I;
118 }
119 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
120 AggregateString);
121 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000122
Ted Kremenek29b72842010-01-07 22:49:05 +0000123 ~ArgsCrashTracerInfo() {
124 ResetCrashTracerInfo(crashtracerSlot);
125 }
126};
127}
128#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000129
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000130/// \brief The result of comparing two source ranges.
131enum RangeComparisonResult {
132 /// \brief Either the ranges overlap or one of the ranges is invalid.
133 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135 /// \brief The first range ends before the second range starts.
136 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000137
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000138 /// \brief The first range starts after the second range ends.
139 RangeAfter
140};
141
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000142/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000143/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000144static RangeComparisonResult RangeCompare(SourceManager &SM,
145 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000146 SourceRange R2) {
147 assert(R1.isValid() && "First range is invalid?");
148 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000149 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000150 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000152 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000153 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000154 return RangeAfter;
155 return RangeOverlap;
156}
157
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000158/// \brief Determine if a source location falls within, before, or after a
159/// a given source range.
160static RangeComparisonResult LocationCompare(SourceManager &SM,
161 SourceLocation L, SourceRange R) {
162 assert(R.isValid() && "First range is invalid?");
163 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000164 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000165 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000166 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
167 return RangeBefore;
168 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
169 return RangeAfter;
170 return RangeOverlap;
171}
172
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000173/// \brief Translate a Clang source range into a CIndex source range.
174///
175/// Clang internally represents ranges where the end location points to the
176/// start of the token at the end. However, for external clients it is more
177/// useful to have a CXSourceRange be a proper half-open interval. This routine
178/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000179CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000180 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000181 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000182 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000183 // location accordingly.
184 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000185 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000186 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000187 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000188 EndLoc = EndLoc.getFileLocWithOffset(Length);
189 }
190
191 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
192 R.getBegin().getRawEncoding(),
193 EndLoc.getRawEncoding() };
194 return Result;
195}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000196
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000197//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000198// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000199//===----------------------------------------------------------------------===//
200
Steve Naroff89922f82009-08-31 00:59:03 +0000201namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000202
Douglas Gregorb1373d02010-01-20 20:59:29 +0000203// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000205 public TypeLocVisitor<CursorVisitor, bool>,
206 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000207{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000209 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000211 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000212 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000213
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000214 /// \brief The declaration that serves at the parent of any statement or
215 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000216 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000217
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000219 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000221 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000222 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000223
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000224 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
225 // to the visitor. Declarations with a PCH level greater than this value will
226 // be suppressed.
227 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000228
229 /// \brief When valid, a source range to which the cursor should restrict
230 /// its search.
231 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000232
Douglas Gregorb1373d02010-01-20 20:59:29 +0000233 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000234 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000235 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000236
237 /// \brief Determine whether this particular source range comes before, comes
238 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000239 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000240 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000241 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
242
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000243 class SetParentRAII {
244 CXCursor &Parent;
245 Decl *&StmtParent;
246 CXCursor OldParent;
247
248 public:
249 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
250 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
251 {
252 Parent = NewParent;
253 if (clang_isDeclaration(Parent.kind))
254 StmtParent = getCursorDecl(Parent);
255 }
256
257 ~SetParentRAII() {
258 Parent = OldParent;
259 if (clang_isDeclaration(Parent.kind))
260 StmtParent = getCursorDecl(Parent);
261 }
262 };
263
Steve Naroff89922f82009-08-31 00:59:03 +0000264public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000265 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
266 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000267 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000268 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000269 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000270 {
271 Parent.kind = CXCursor_NoDeclFound;
272 Parent.data[0] = 0;
273 Parent.data[1] = 0;
274 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000275 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000276 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000277
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000278 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000279
280 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
281 getPreprocessedEntities();
282
Douglas Gregorb1373d02010-01-20 20:59:29 +0000283 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000284
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000285 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000286 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000287 bool VisitBlockDecl(BlockDecl *B);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000288 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000289 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
290 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000291 bool VisitTagDecl(TagDecl *D);
292 bool VisitEnumConstantDecl(EnumConstantDecl *D);
293 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
294 bool VisitFunctionDecl(FunctionDecl *ND);
295 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000296 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000297 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
298 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
299 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
300 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000301 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000302 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
303 bool VisitObjCImplDecl(ObjCImplDecl *D);
304 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
305 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
306 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
307 // etc.
308 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
309 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
310 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000311 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000312 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000313
314 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000315 // FIXME: QualifiedTypeLoc doesn't provide any location information
316 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000317 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000318 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
319 bool VisitTagTypeLoc(TagTypeLoc TL);
320 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
321 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000322 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000323 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
324 bool VisitPointerTypeLoc(PointerTypeLoc TL);
325 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
326 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
327 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
328 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
329 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
330 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000331 // FIXME: Implement for TemplateSpecializationTypeLoc
332 // FIXME: Implement visitors here when the unimplemented TypeLocs get
333 // implemented
334 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
335 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000336
Douglas Gregora59e3902010-01-21 23:27:09 +0000337 // Statement visitors
338 bool VisitStmt(Stmt *S);
339 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000340 // FIXME: LabelStmt label?
341 bool VisitIfStmt(IfStmt *S);
342 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000343 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000344 bool VisitWhileStmt(WhileStmt *S);
345 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000346// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000347
Douglas Gregor336fd812010-01-23 00:40:08 +0000348 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000349 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
350 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000351 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000352 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000353 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000354 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000355 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000356 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000357 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000358 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000359 // FIXME: AddrLabelExpr (once we have cursors for labels)
360 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
361 bool VisitVAArgExpr(VAArgExpr *E);
362 // FIXME: InitListExpr (for the designators)
363 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000364};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000365
Ted Kremenekab188932010-01-05 19:32:54 +0000366} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000367
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000368static SourceRange getRawCursorExtent(CXCursor C);
369
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000370RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000371 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
372}
373
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374/// \brief Visit the given cursor and, if requested by the visitor,
375/// its children.
376///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000377/// \param Cursor the cursor to visit.
378///
379/// \param CheckRegionOfInterest if true, then the caller already checked that
380/// this cursor is within the region of interest.
381///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000382/// \returns true if the visitation should be aborted, false if it
383/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000384bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000385 if (clang_isInvalid(Cursor.kind))
386 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000387
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388 if (clang_isDeclaration(Cursor.kind)) {
389 Decl *D = getCursorDecl(Cursor);
390 assert(D && "Invalid declaration cursor");
391 if (D->getPCHLevel() > MaxPCHLevel)
392 return false;
393
394 if (D->isImplicit())
395 return false;
396 }
397
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000398 // If we have a range of interest, and this cursor doesn't intersect with it,
399 // we're done.
400 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000401 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000402 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000403 return false;
404 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000405
Douglas Gregorb1373d02010-01-20 20:59:29 +0000406 switch (Visitor(Cursor, Parent, ClientData)) {
407 case CXChildVisit_Break:
408 return true;
409
410 case CXChildVisit_Continue:
411 return false;
412
413 case CXChildVisit_Recurse:
414 return VisitChildren(Cursor);
415 }
416
Douglas Gregorfd643772010-01-25 16:45:46 +0000417 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418}
419
Douglas Gregor788f5a12010-03-20 00:41:21 +0000420std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
421CursorVisitor::getPreprocessedEntities() {
422 PreprocessingRecord &PPRec
423 = *TU->getPreprocessor().getPreprocessingRecord();
424
425 bool OnlyLocalDecls
426 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
427
428 // There is no region of interest; we have to walk everything.
429 if (RegionOfInterest.isInvalid())
430 return std::make_pair(PPRec.begin(OnlyLocalDecls),
431 PPRec.end(OnlyLocalDecls));
432
433 // Find the file in which the region of interest lands.
434 SourceManager &SM = TU->getSourceManager();
435 std::pair<FileID, unsigned> Begin
436 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
437 std::pair<FileID, unsigned> End
438 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
439
440 // The region of interest spans files; we have to walk everything.
441 if (Begin.first != End.first)
442 return std::make_pair(PPRec.begin(OnlyLocalDecls),
443 PPRec.end(OnlyLocalDecls));
444
445 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
446 = TU->getPreprocessedEntitiesByFile();
447 if (ByFileMap.empty()) {
448 // Build the mapping from files to sets of preprocessed entities.
449 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
450 EEnd = PPRec.end(OnlyLocalDecls);
451 E != EEnd; ++E) {
452 std::pair<FileID, unsigned> P
453 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
454 ByFileMap[P.first].push_back(*E);
455 }
456 }
457
458 return std::make_pair(ByFileMap[Begin.first].begin(),
459 ByFileMap[Begin.first].end());
460}
461
Douglas Gregorb1373d02010-01-20 20:59:29 +0000462/// \brief Visit the children of the given cursor.
463///
464/// \returns true if the visitation should be aborted, false if it
465/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000466bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000467 if (clang_isReference(Cursor.kind)) {
468 // By definition, references have no children.
469 return false;
470 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000471
472 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000473 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000474 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000475
Douglas Gregorb1373d02010-01-20 20:59:29 +0000476 if (clang_isDeclaration(Cursor.kind)) {
477 Decl *D = getCursorDecl(Cursor);
478 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000479 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000480 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000481
Douglas Gregora59e3902010-01-21 23:27:09 +0000482 if (clang_isStatement(Cursor.kind))
483 return Visit(getCursorStmt(Cursor));
484 if (clang_isExpression(Cursor.kind))
485 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000486
Douglas Gregorb1373d02010-01-20 20:59:29 +0000487 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000488 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000489 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
490 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000491 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
492 TLEnd = CXXUnit->top_level_end();
493 TL != TLEnd; ++TL) {
494 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000495 return true;
496 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000497 } else if (VisitDeclContext(
498 CXXUnit->getASTContext().getTranslationUnitDecl()))
499 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000500
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000502 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000503 // FIXME: Once we have the ability to deserialize a preprocessing record,
504 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000505 PreprocessingRecord::iterator E, EEnd;
506 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000507 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
508 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
509 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000510
Douglas Gregor0396f462010-03-19 05:22:59 +0000511 continue;
512 }
513
514 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
515 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
516 return true;
517
518 continue;
519 }
520 }
521 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000522 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000523 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000524
Douglas Gregorb1373d02010-01-20 20:59:29 +0000525 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 return false;
527}
528
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000529bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000530 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
531 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000532
Ted Kremenek664cffd2010-07-22 11:30:19 +0000533 if (Stmt *Body = B->getBody())
534 return Visit(MakeCXCursor(Body, StmtParent, TU));
535
536 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000537}
538
Douglas Gregorb1373d02010-01-20 20:59:29 +0000539bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000540 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000541 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000542
Ted Kremenek23173d72010-05-18 21:09:07 +0000543 Decl *D = *I;
544 if (D->getLexicalDeclContext() != DC)
545 continue;
546
547 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000548
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000549 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000550 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000551 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000552 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000553
554 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000555 case RangeBefore:
556 // This declaration comes before the region of interest; skip it.
557 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000558
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000559 case RangeAfter:
560 // This declaration comes after the region of interest; we're done.
561 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000562
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000563 case RangeOverlap:
564 // This declaration overlaps the region of interest; visit it.
565 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000566 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000567 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000568
Daniel Dunbard52864b2010-02-14 10:02:57 +0000569 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000570 return true;
571 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000572
Douglas Gregorb1373d02010-01-20 20:59:29 +0000573 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000574}
575
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000576bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
577 llvm_unreachable("Translation units are visited directly by Visit()");
578 return false;
579}
580
581bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
582 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
583 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000584
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000585 return false;
586}
587
588bool CursorVisitor::VisitTagDecl(TagDecl *D) {
589 return VisitDeclContext(D);
590}
591
592bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
593 if (Expr *Init = D->getInitExpr())
594 return Visit(MakeCXCursor(Init, StmtParent, TU));
595 return false;
596}
597
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000598bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
599 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
600 if (Visit(TSInfo->getTypeLoc()))
601 return true;
602
603 return false;
604}
605
Douglas Gregorb1373d02010-01-20 20:59:29 +0000606bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000607 if (VisitDeclaratorDecl(ND))
608 return true;
609
Douglas Gregora59e3902010-01-21 23:27:09 +0000610 if (ND->isThisDeclarationADefinition() &&
611 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
612 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000613
Douglas Gregorb1373d02010-01-20 20:59:29 +0000614 return false;
615}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000616
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000617bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
618 if (VisitDeclaratorDecl(D))
619 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000620
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000621 if (Expr *BitWidth = D->getBitWidth())
622 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000623
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000624 return false;
625}
626
627bool CursorVisitor::VisitVarDecl(VarDecl *D) {
628 if (VisitDeclaratorDecl(D))
629 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000630
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000631 if (Expr *Init = D->getInit())
632 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000633
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000634 return false;
635}
636
637bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000638 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
639 if (Visit(TSInfo->getTypeLoc()))
640 return true;
641
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000642 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000643 PEnd = ND->param_end();
644 P != PEnd; ++P) {
645 if (Visit(MakeCXCursor(*P, TU)))
646 return true;
647 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000648
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000649 if (ND->isThisDeclarationADefinition() &&
650 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
651 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000652
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000653 return false;
654}
655
Douglas Gregora59e3902010-01-21 23:27:09 +0000656bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
657 return VisitDeclContext(D);
658}
659
Douglas Gregorb1373d02010-01-20 20:59:29 +0000660bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000661 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
662 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000663 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000664
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000665 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
666 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
667 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000668 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000669 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000670
Douglas Gregora59e3902010-01-21 23:27:09 +0000671 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000672}
673
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000674bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
675 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
676 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
677 E = PID->protocol_end(); I != E; ++I, ++PL)
678 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
679 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000680
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000681 return VisitObjCContainerDecl(PID);
682}
683
Ted Kremenek23173d72010-05-18 21:09:07 +0000684bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000685 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
686 return true;
687
Ted Kremenek23173d72010-05-18 21:09:07 +0000688 // FIXME: This implements a workaround with @property declarations also being
689 // installed in the DeclContext for the @interface. Eventually this code
690 // should be removed.
691 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
692 if (!CDecl || !CDecl->IsClassExtension())
693 return false;
694
695 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
696 if (!ID)
697 return false;
698
699 IdentifierInfo *PropertyId = PD->getIdentifier();
700 ObjCPropertyDecl *prevDecl =
701 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
702
703 if (!prevDecl)
704 return false;
705
706 // Visit synthesized methods since they will be skipped when visiting
707 // the @interface.
708 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
709 if (MD->isSynthesized())
710 if (Visit(MakeCXCursor(MD, TU)))
711 return true;
712
713 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
714 if (MD->isSynthesized())
715 if (Visit(MakeCXCursor(MD, TU)))
716 return true;
717
718 return false;
719}
720
Douglas Gregorb1373d02010-01-20 20:59:29 +0000721bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000722 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000723 if (D->getSuperClass() &&
724 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000725 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000726 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000727 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000728
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000729 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
730 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
731 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000732 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000733 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000734
Douglas Gregora59e3902010-01-21 23:27:09 +0000735 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000736}
737
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000738bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
739 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000740}
741
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000742bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000743 // 'ID' could be null when dealing with invalid code.
744 if (ObjCInterfaceDecl *ID = D->getClassInterface())
745 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
746 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000747
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000748 return VisitObjCImplDecl(D);
749}
750
751bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
752#if 0
753 // Issue callbacks for super class.
754 // FIXME: No source location information!
755 if (D->getSuperClass() &&
756 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000757 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000758 TU)))
759 return true;
760#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000761
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000762 return VisitObjCImplDecl(D);
763}
764
765bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
766 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
767 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
768 E = D->protocol_end();
769 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000770 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000771 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000772
773 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000774}
775
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000776bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
777 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
778 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
779 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000780
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000781 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000782}
783
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000784bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
785 return VisitDeclContext(D);
786}
787
Ted Kremeneka0536d82010-05-07 01:04:29 +0000788bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
789 return VisitDeclContext(D);
790}
791
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000792bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
793 ASTContext &Context = TU->getASTContext();
794
795 // Some builtin types (such as Objective-C's "id", "sel", and
796 // "Class") have associated declarations. Create cursors for those.
797 QualType VisitType;
798 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000799 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000800 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000801 case BuiltinType::Char_U:
802 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000803 case BuiltinType::Char16:
804 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000805 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000806 case BuiltinType::UInt:
807 case BuiltinType::ULong:
808 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000809 case BuiltinType::UInt128:
810 case BuiltinType::Char_S:
811 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000812 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000813 case BuiltinType::Short:
814 case BuiltinType::Int:
815 case BuiltinType::Long:
816 case BuiltinType::LongLong:
817 case BuiltinType::Int128:
818 case BuiltinType::Float:
819 case BuiltinType::Double:
820 case BuiltinType::LongDouble:
821 case BuiltinType::NullPtr:
822 case BuiltinType::Overload:
823 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000824 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000825
826 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000827 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000828
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000829 case BuiltinType::ObjCId:
830 VisitType = Context.getObjCIdType();
831 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000832
833 case BuiltinType::ObjCClass:
834 VisitType = Context.getObjCClassType();
835 break;
836
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000837 case BuiltinType::ObjCSel:
838 VisitType = Context.getObjCSelType();
839 break;
840 }
841
842 if (!VisitType.isNull()) {
843 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000844 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000845 TU));
846 }
847
848 return false;
849}
850
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000851bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
852 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
853}
854
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000855bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
856 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
857}
858
859bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
860 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
861}
862
863bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
864 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
865 return true;
866
John McCallc12c5bb2010-05-15 11:32:37 +0000867 return false;
868}
869
870bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
871 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
872 return true;
873
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000874 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
875 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
876 TU)))
877 return true;
878 }
879
880 return false;
881}
882
883bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +0000884 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000885}
886
887bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
888 return Visit(TL.getPointeeLoc());
889}
890
891bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
892 return Visit(TL.getPointeeLoc());
893}
894
895bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
896 return Visit(TL.getPointeeLoc());
897}
898
899bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000900 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000901}
902
903bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000904 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000905}
906
907bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
908 if (Visit(TL.getResultLoc()))
909 return true;
910
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000911 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000912 if (Decl *D = TL.getArg(I))
913 if (Visit(MakeCXCursor(D, TU)))
914 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000915
916 return false;
917}
918
919bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
920 if (Visit(TL.getElementLoc()))
921 return true;
922
923 if (Expr *Size = TL.getSizeExpr())
924 return Visit(MakeCXCursor(Size, StmtParent, TU));
925
926 return false;
927}
928
Douglas Gregor2332c112010-01-21 20:48:56 +0000929bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
930 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
931}
932
933bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
934 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
935 return Visit(TSInfo->getTypeLoc());
936
937 return false;
938}
939
Douglas Gregora59e3902010-01-21 23:27:09 +0000940bool CursorVisitor::VisitStmt(Stmt *S) {
941 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
942 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000943 if (Stmt *C = *Child)
944 if (Visit(MakeCXCursor(C, StmtParent, TU)))
945 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +0000946 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000947
Douglas Gregora59e3902010-01-21 23:27:09 +0000948 return false;
949}
950
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000951bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
952 // Specially handle CaseStmts because they can be nested, e.g.:
953 //
954 // case 1:
955 // case 2:
956 //
957 // In this case the second CaseStmt is the child of the first. Walking
958 // these recursively can blow out the stack.
959 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
960 while (true) {
961 // Set the Parent field to Cursor, then back to its old value once we're
962 // done.
963 SetParentRAII SetParent(Parent, StmtParent, Cursor);
964
965 if (Stmt *LHS = S->getLHS())
966 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
967 return true;
968 if (Stmt *RHS = S->getRHS())
969 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
970 return true;
971 if (Stmt *SubStmt = S->getSubStmt()) {
972 if (!isa<CaseStmt>(SubStmt))
973 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
974
975 // Specially handle 'CaseStmt' so that we don't blow out the stack.
976 CaseStmt *CS = cast<CaseStmt>(SubStmt);
977 Cursor = MakeCXCursor(CS, StmtParent, TU);
978 if (RegionOfInterest.isValid()) {
979 SourceRange Range = CS->getSourceRange();
980 if (Range.isInvalid() || CompareRegionOfInterest(Range))
981 return false;
982 }
983
984 switch (Visitor(Cursor, Parent, ClientData)) {
985 case CXChildVisit_Break: return true;
986 case CXChildVisit_Continue: return false;
987 case CXChildVisit_Recurse:
988 // Perform tail-recursion manually.
989 S = CS;
990 continue;
991 }
992 }
993 return false;
994 }
995}
996
Douglas Gregora59e3902010-01-21 23:27:09 +0000997bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
998 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
999 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001000 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001001 return true;
1002 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001003
Douglas Gregora59e3902010-01-21 23:27:09 +00001004 return false;
1005}
1006
Douglas Gregorf5bab412010-01-22 01:00:11 +00001007bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1008 if (VarDecl *Var = S->getConditionVariable()) {
1009 if (Visit(MakeCXCursor(Var, TU)))
1010 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001011 }
1012
Douglas Gregor263b47b2010-01-25 16:12:32 +00001013 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1014 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001015 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1016 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001017 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1018 return true;
1019
1020 return false;
1021}
1022
1023bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1024 if (VarDecl *Var = S->getConditionVariable()) {
1025 if (Visit(MakeCXCursor(Var, TU)))
1026 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027 }
1028
Douglas Gregor263b47b2010-01-25 16:12:32 +00001029 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1030 return true;
1031 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1032 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001033
Douglas Gregor263b47b2010-01-25 16:12:32 +00001034 return false;
1035}
1036
1037bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1038 if (VarDecl *Var = S->getConditionVariable()) {
1039 if (Visit(MakeCXCursor(Var, TU)))
1040 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001041 }
1042
Douglas Gregor263b47b2010-01-25 16:12:32 +00001043 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1044 return true;
1045 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001046 return true;
1047
Douglas Gregor263b47b2010-01-25 16:12:32 +00001048 return false;
1049}
1050
1051bool CursorVisitor::VisitForStmt(ForStmt *S) {
1052 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1053 return true;
1054 if (VarDecl *Var = S->getConditionVariable()) {
1055 if (Visit(MakeCXCursor(Var, TU)))
1056 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001057 }
1058
Douglas Gregor263b47b2010-01-25 16:12:32 +00001059 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1060 return true;
1061 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1062 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001063 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1064 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001065
Douglas Gregorf5bab412010-01-22 01:00:11 +00001066 return false;
1067}
1068
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001069bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1070 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1071 return true;
1072
1073 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1074 return true;
1075
1076 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1077 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1078 return true;
1079
1080 return false;
1081}
1082
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001083bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1084 return Visit(B->getBlockDecl());
1085}
1086
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001087bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1088 // FIXME: Visit fields as well?
1089 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1090 return true;
1091
1092 return VisitExpr(E);
1093}
1094
Douglas Gregor336fd812010-01-23 00:40:08 +00001095bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1096 if (E->isArgumentType()) {
1097 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1098 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001099
Douglas Gregor336fd812010-01-23 00:40:08 +00001100 return false;
1101 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001102
Douglas Gregor336fd812010-01-23 00:40:08 +00001103 return VisitExpr(E);
1104}
1105
1106bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1107 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1108 if (Visit(TSInfo->getTypeLoc()))
1109 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001110
Douglas Gregor336fd812010-01-23 00:40:08 +00001111 return VisitCastExpr(E);
1112}
1113
1114bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1115 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1116 if (Visit(TSInfo->getTypeLoc()))
1117 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001118
Douglas Gregor336fd812010-01-23 00:40:08 +00001119 return VisitExpr(E);
1120}
1121
Douglas Gregor648220e2010-08-10 15:02:34 +00001122bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1123 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1124 Visit(E->getArgTInfo2()->getTypeLoc());
1125}
1126
1127bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1128 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1129 return true;
1130
1131 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1132}
1133
Douglas Gregorc2350e52010-03-08 16:40:19 +00001134bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001135 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1136 if (Visit(TSInfo->getTypeLoc()))
1137 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001138
1139 return VisitExpr(E);
1140}
1141
Douglas Gregor81d34662010-04-20 15:39:42 +00001142bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1143 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1144}
1145
1146
Ted Kremenek09dfa372010-02-18 05:46:33 +00001147bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001148 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1149 i != e; ++i)
1150 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001151 return true;
1152
1153 return false;
1154}
1155
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001156extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001157CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1158 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001159 // We use crash recovery to make some of our APIs more reliable, implicitly
1160 // enable it.
1161 llvm::CrashRecoveryContext::Enable();
1162
Douglas Gregora030b7c2010-01-22 20:35:53 +00001163 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001164 if (excludeDeclarationsFromPCH)
1165 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001166 if (displayDiagnostics)
1167 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001168 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001169}
1170
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001171void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001172 if (CIdx)
1173 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001174 if (getenv("LIBCLANG_TIMING"))
1175 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001176}
1177
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001178void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001179 if (CIdx) {
1180 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1181 CXXIdx->setUseExternalASTGeneration(value);
1182 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001183}
1184
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001185CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001186 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001187 if (!CIdx)
1188 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001189
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001190 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001191
Douglas Gregor28019772010-04-05 23:52:57 +00001192 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001193 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001194 CXXIdx->getOnlyLocalDecls(),
1195 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001196}
1197
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001198unsigned clang_defaultEditingTranslationUnitOptions() {
1199 return CXTranslationUnit_PrecompiledPreamble;
1200}
1201
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001202CXTranslationUnit
1203clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1204 const char *source_filename,
1205 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001206 const char **command_line_args,
1207 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001208 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001209 return clang_parseTranslationUnit(CIdx, source_filename,
1210 command_line_args, num_command_line_args,
1211 unsaved_files, num_unsaved_files,
1212 CXTranslationUnit_DetailedPreprocessingRecord);
1213}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001214
1215struct ParseTranslationUnitInfo {
1216 CXIndex CIdx;
1217 const char *source_filename;
1218 const char **command_line_args;
1219 int num_command_line_args;
1220 struct CXUnsavedFile *unsaved_files;
1221 unsigned num_unsaved_files;
1222 unsigned options;
1223 CXTranslationUnit result;
1224};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001225static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001226 ParseTranslationUnitInfo *PTUI =
1227 static_cast<ParseTranslationUnitInfo*>(UserData);
1228 CXIndex CIdx = PTUI->CIdx;
1229 const char *source_filename = PTUI->source_filename;
1230 const char **command_line_args = PTUI->command_line_args;
1231 int num_command_line_args = PTUI->num_command_line_args;
1232 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1233 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1234 unsigned options = PTUI->options;
1235 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001236
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001237 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001238 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001239
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001240 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1241
Douglas Gregor44c181a2010-07-23 00:33:23 +00001242 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001243 bool CompleteTranslationUnit
1244 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001245 bool CacheCodeCompetionResults
1246 = options & CXTranslationUnit_CacheCompletionResults;
1247
Douglas Gregor5352ac02010-01-28 00:27:43 +00001248 // Configure the diagnostics.
1249 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001250 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1251 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001252
Douglas Gregor4db64a42010-01-23 00:14:00 +00001253 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1254 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001255 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001256 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001257 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001258 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1259 Buffer));
1260 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001261
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001262 if (!CXXIdx->getUseExternalASTGeneration()) {
1263 llvm::SmallVector<const char *, 16> Args;
1264
1265 // The 'source_filename' argument is optional. If the caller does not
1266 // specify it then it is assumed that the source file is specified
1267 // in the actual argument list.
1268 if (source_filename)
1269 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001270
1271 // Since the Clang C library is primarily used by batch tools dealing with
1272 // (often very broken) source code, where spell-checking can have a
1273 // significant negative impact on performance (particularly when
1274 // precompiled headers are involved), we disable it by default.
1275 // Note that we place this argument early in the list, so that it can be
1276 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001277 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001278
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001279 Args.insert(Args.end(), command_line_args,
1280 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001281
Douglas Gregor44c181a2010-07-23 00:33:23 +00001282 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001283 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1284 Args.push_back("-Xclang");
1285 Args.push_back("-detailed-preprocessing-record");
1286 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001287
Douglas Gregor5352ac02010-01-28 00:27:43 +00001288 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001289
Ted Kremenek29b72842010-01-07 22:49:05 +00001290#ifdef USE_CRASHTRACER
1291 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001292#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001293
Daniel Dunbar94220972009-12-05 02:17:18 +00001294 llvm::OwningPtr<ASTUnit> Unit(
1295 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001296 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001297 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001298 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001299 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001300 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001301 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001302 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001303 CompleteTranslationUnit,
1304 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001305
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001306 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001307 // Make sure to check that 'Unit' is non-NULL.
1308 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001309 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1310 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001311 D != DEnd; ++D) {
1312 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001313 CXString Msg = clang_formatDiagnostic(&Diag,
1314 clang_defaultDiagnosticDisplayOptions());
1315 fprintf(stderr, "%s\n", clang_getCString(Msg));
1316 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001317 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001318#ifdef LLVM_ON_WIN32
1319 // On Windows, force a flush, since there may be multiple copies of
1320 // stderr and stdout in the file system, all with different buffers
1321 // but writing to the same device.
1322 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001323#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001324 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001325 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001326
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001327 PTUI->result = Unit.take();
1328 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001329 }
1330
Ted Kremenek139ba862009-10-22 00:03:57 +00001331 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001332 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001333
Ted Kremenek139ba862009-10-22 00:03:57 +00001334 // First add the complete path to the 'clang' executable.
1335 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001336 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001337
Ted Kremenek139ba862009-10-22 00:03:57 +00001338 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001339 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001340
Ted Kremenek139ba862009-10-22 00:03:57 +00001341 // The 'source_filename' argument is optional. If the caller does not
1342 // specify it then it is assumed that the source file is specified
1343 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001344 if (source_filename)
1345 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001346
Steve Naroff37b5ac22009-10-15 20:50:09 +00001347 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001348 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001349 char astTmpFile[L_tmpnam];
1350 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001351
1352 // Since the Clang C library is primarily used by batch tools dealing with
1353 // (often very broken) source code, where spell-checking can have a
1354 // significant negative impact on performance (particularly when
1355 // precompiled headers are involved), we disable it by default.
1356 // Note that we place this argument early in the list, so that it can be
1357 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001358 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001359
Douglas Gregor4db64a42010-01-23 00:14:00 +00001360 // Remap any unsaved files to temporary files.
1361 std::vector<llvm::sys::Path> TemporaryFiles;
1362 std::vector<std::string> RemapArgs;
1363 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001364 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001365
Douglas Gregor4db64a42010-01-23 00:14:00 +00001366 // The pointers into the elements of RemapArgs are stable because we
1367 // won't be adding anything to RemapArgs after this point.
1368 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1369 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001370
Ted Kremenek139ba862009-10-22 00:03:57 +00001371 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1372 for (int i = 0; i < num_command_line_args; ++i)
1373 if (const char *arg = command_line_args[i]) {
1374 if (strcmp(arg, "-o") == 0) {
1375 ++i; // Also skip the matching argument.
1376 continue;
1377 }
1378 if (strcmp(arg, "-emit-ast") == 0 ||
1379 strcmp(arg, "-c") == 0 ||
1380 strcmp(arg, "-fsyntax-only") == 0) {
1381 continue;
1382 }
1383
1384 // Keep the argument.
1385 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001386 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001387
Douglas Gregord93256e2010-01-28 06:00:51 +00001388 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001389 char tmpFileResults[L_tmpnam];
1390 char *tmpResultsFileName = tmpnam(tmpFileResults);
1391 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001392 TemporaryFiles.push_back(DiagnosticsFile);
1393 argv.push_back("-fdiagnostics-binary");
1394
Douglas Gregor44c181a2010-07-23 00:33:23 +00001395 // Do we need the detailed preprocessing record?
1396 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1397 argv.push_back("-Xclang");
1398 argv.push_back("-detailed-preprocessing-record");
1399 }
1400
Ted Kremenek139ba862009-10-22 00:03:57 +00001401 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001402 argv.push_back(NULL);
1403
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001404 // Invoke 'clang'.
1405 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1406 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001407 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001408 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1409 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001410 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001411 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001412 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001413
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001414 if (!ErrMsg.empty()) {
1415 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001416 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001417 I != E; ++I) {
1418 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001419 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001420 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001421 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001422
Daniel Dunbar32141c82010-02-23 20:23:45 +00001423 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001424 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001425
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001426 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001427 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001428 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001429 RemappedFiles.size(),
1430 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001431 if (ATU) {
1432 LoadSerializedDiagnostics(DiagnosticsFile,
1433 num_unsaved_files, unsaved_files,
1434 ATU->getFileManager(),
1435 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001436 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001437 } else if (CXXIdx->getDisplayDiagnostics()) {
1438 // We failed to load the ASTUnit, but we can still deserialize the
1439 // diagnostics and emit them.
1440 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001441 Diagnostic Diag;
1442 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001443 // FIXME: Faked LangOpts!
1444 LangOptions LangOpts;
1445 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1446 LoadSerializedDiagnostics(DiagnosticsFile,
1447 num_unsaved_files, unsaved_files,
1448 FileMgr, SourceMgr, Diags);
1449 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1450 DEnd = Diags.end();
1451 D != DEnd; ++D) {
1452 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001453 CXString Msg = clang_formatDiagnostic(&Diag,
1454 clang_defaultDiagnosticDisplayOptions());
1455 fprintf(stderr, "%s\n", clang_getCString(Msg));
1456 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001457 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001458
1459#ifdef LLVM_ON_WIN32
1460 // On Windows, force a flush, since there may be multiple copies of
1461 // stderr and stdout in the file system, all with different buffers
1462 // but writing to the same device.
1463 fflush(stderr);
1464#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001465 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001466
Douglas Gregor313e26c2010-02-18 23:35:40 +00001467 if (ATU) {
1468 // Make the translation unit responsible for destroying all temporary files.
1469 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1470 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001471 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001472 } else {
1473 // Destroy all of the temporary files now; they can't be referenced any
1474 // longer.
1475 llvm::sys::Path(astTmpFile).eraseFromDisk();
1476 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1477 TemporaryFiles[i].eraseFromDisk();
1478 }
1479
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001480 PTUI->result = ATU;
1481}
1482CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1483 const char *source_filename,
1484 const char **command_line_args,
1485 int num_command_line_args,
1486 struct CXUnsavedFile *unsaved_files,
1487 unsigned num_unsaved_files,
1488 unsigned options) {
1489 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1490 num_command_line_args, unsaved_files, num_unsaved_files,
1491 options, 0 };
1492 llvm::CrashRecoveryContext CRC;
1493
1494 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001495 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1496 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1497 fprintf(stderr, " 'command_line_args' : [");
1498 for (int i = 0; i != num_command_line_args; ++i) {
1499 if (i)
1500 fprintf(stderr, ", ");
1501 fprintf(stderr, "'%s'", command_line_args[i]);
1502 }
1503 fprintf(stderr, "],\n");
1504 fprintf(stderr, " 'unsaved_files' : [");
1505 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1506 if (i)
1507 fprintf(stderr, ", ");
1508 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1509 unsaved_files[i].Length);
1510 }
1511 fprintf(stderr, "],\n");
1512 fprintf(stderr, " 'options' : %d,\n", options);
1513 fprintf(stderr, "}\n");
1514
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001515 return 0;
1516 }
1517
1518 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001519}
1520
Douglas Gregor19998442010-08-13 15:35:05 +00001521unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1522 return CXSaveTranslationUnit_None;
1523}
1524
1525int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1526 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001527 if (!TU)
1528 return 1;
1529
1530 return static_cast<ASTUnit *>(TU)->Save(FileName);
1531}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001532
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001533void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001534 if (CTUnit) {
1535 // If the translation unit has been marked as unsafe to free, just discard
1536 // it.
1537 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1538 return;
1539
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001540 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001541 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001542}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001543
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001544unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1545 return CXReparse_None;
1546}
1547
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001548struct ReparseTranslationUnitInfo {
1549 CXTranslationUnit TU;
1550 unsigned num_unsaved_files;
1551 struct CXUnsavedFile *unsaved_files;
1552 unsigned options;
1553 int result;
1554};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001555static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001556 ReparseTranslationUnitInfo *RTUI =
1557 static_cast<ReparseTranslationUnitInfo*>(UserData);
1558 CXTranslationUnit TU = RTUI->TU;
1559 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1560 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1561 unsigned options = RTUI->options;
1562 (void) options;
1563 RTUI->result = 1;
1564
Douglas Gregorabc563f2010-07-19 21:46:24 +00001565 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001566 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001567
1568 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1569 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1570 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1571 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001572 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001573 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1574 Buffer));
1575 }
1576
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001577 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1578 RemappedFiles.size()))
1579 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001580}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001581int clang_reparseTranslationUnit(CXTranslationUnit TU,
1582 unsigned num_unsaved_files,
1583 struct CXUnsavedFile *unsaved_files,
1584 unsigned options) {
1585 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1586 options, 0 };
1587 llvm::CrashRecoveryContext CRC;
1588
1589 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001590 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001591 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1592 return 1;
1593 }
1594
1595 return RTUI.result;
1596}
1597
Douglas Gregordf95a132010-08-09 20:45:32 +00001598
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001599CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001600 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001601 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001602
Steve Naroff77accc12009-09-03 18:19:54 +00001603 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001604 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001605}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001606
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001607CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001608 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001609 return Result;
1610}
1611
Ted Kremenekfb480492010-01-13 21:46:36 +00001612} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001613
Ted Kremenekfb480492010-01-13 21:46:36 +00001614//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001615// CXSourceLocation and CXSourceRange Operations.
1616//===----------------------------------------------------------------------===//
1617
Douglas Gregorb9790342010-01-22 21:44:22 +00001618extern "C" {
1619CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001620 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001621 return Result;
1622}
1623
1624unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001625 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1626 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1627 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001628}
1629
1630CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1631 CXFile file,
1632 unsigned line,
1633 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001634 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001635 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001636
Douglas Gregorb9790342010-01-22 21:44:22 +00001637 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1638 SourceLocation SLoc
1639 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001640 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001641 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001642
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001643 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001644}
1645
Douglas Gregor5352ac02010-01-28 00:27:43 +00001646CXSourceRange clang_getNullRange() {
1647 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1648 return Result;
1649}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001650
Douglas Gregor5352ac02010-01-28 00:27:43 +00001651CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1652 if (begin.ptr_data[0] != end.ptr_data[0] ||
1653 begin.ptr_data[1] != end.ptr_data[1])
1654 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001655
1656 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001657 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001658 return Result;
1659}
1660
Douglas Gregor46766dc2010-01-26 19:19:08 +00001661void clang_getInstantiationLocation(CXSourceLocation location,
1662 CXFile *file,
1663 unsigned *line,
1664 unsigned *column,
1665 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001666 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1667
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001668 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001669 if (file)
1670 *file = 0;
1671 if (line)
1672 *line = 0;
1673 if (column)
1674 *column = 0;
1675 if (offset)
1676 *offset = 0;
1677 return;
1678 }
1679
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001680 const SourceManager &SM =
1681 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001682 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001683
1684 if (file)
1685 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1686 if (line)
1687 *line = SM.getInstantiationLineNumber(InstLoc);
1688 if (column)
1689 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001690 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001691 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001692}
1693
Douglas Gregor1db19de2010-01-19 21:36:55 +00001694CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001695 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001696 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001697 return Result;
1698}
1699
1700CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001701 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001702 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001703 return Result;
1704}
1705
Douglas Gregorb9790342010-01-22 21:44:22 +00001706} // end: extern "C"
1707
Douglas Gregor1db19de2010-01-19 21:36:55 +00001708//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001709// CXFile Operations.
1710//===----------------------------------------------------------------------===//
1711
1712extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001713CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001714 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001715 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001716
Steve Naroff88145032009-10-27 14:35:18 +00001717 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001718 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001719}
1720
1721time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001722 if (!SFile)
1723 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001724
Steve Naroff88145032009-10-27 14:35:18 +00001725 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1726 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001727}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001728
Douglas Gregorb9790342010-01-22 21:44:22 +00001729CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1730 if (!tu)
1731 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001732
Douglas Gregorb9790342010-01-22 21:44:22 +00001733 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001734
Douglas Gregorb9790342010-01-22 21:44:22 +00001735 FileManager &FMgr = CXXUnit->getFileManager();
1736 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1737 return const_cast<FileEntry *>(File);
1738}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001739
Ted Kremenekfb480492010-01-13 21:46:36 +00001740} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001741
Ted Kremenekfb480492010-01-13 21:46:36 +00001742//===----------------------------------------------------------------------===//
1743// CXCursor Operations.
1744//===----------------------------------------------------------------------===//
1745
Ted Kremenekfb480492010-01-13 21:46:36 +00001746static Decl *getDeclFromExpr(Stmt *E) {
1747 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1748 return RefExpr->getDecl();
1749 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1750 return ME->getMemberDecl();
1751 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1752 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001753
Ted Kremenekfb480492010-01-13 21:46:36 +00001754 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1755 return getDeclFromExpr(CE->getCallee());
1756 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1757 return getDeclFromExpr(CE->getSubExpr());
1758 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1759 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001760
Ted Kremenekfb480492010-01-13 21:46:36 +00001761 return 0;
1762}
1763
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001764static SourceLocation getLocationFromExpr(Expr *E) {
1765 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1766 return /*FIXME:*/Msg->getLeftLoc();
1767 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1768 return DRE->getLocation();
1769 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1770 return Member->getMemberLoc();
1771 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1772 return Ivar->getLocation();
1773 return E->getLocStart();
1774}
1775
Ted Kremenekfb480492010-01-13 21:46:36 +00001776extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001777
1778unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001779 CXCursorVisitor visitor,
1780 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001781 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001782
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001783 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1784 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00001785 return CursorVis.VisitChildren(parent);
1786}
1787
Douglas Gregor78205d42010-01-20 21:45:58 +00001788static CXString getDeclSpelling(Decl *D) {
1789 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1790 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001791 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001792
Douglas Gregor78205d42010-01-20 21:45:58 +00001793 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001794 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001795
Douglas Gregor78205d42010-01-20 21:45:58 +00001796 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1797 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1798 // and returns different names. NamedDecl returns the class name and
1799 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001800 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001801
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001802 llvm::SmallString<1024> S;
1803 llvm::raw_svector_ostream os(S);
1804 ND->printName(os);
1805
1806 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001807}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001808
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001809CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001810 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001811 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001812
Steve Narofff334b4e2009-09-02 18:26:48 +00001813 if (clang_isReference(C.kind)) {
1814 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001815 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001816 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001817 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001818 }
1819 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001820 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001821 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001822 }
1823 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001824 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001825 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001826 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001827 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001828 case CXCursor_TypeRef: {
1829 TypeDecl *Type = getCursorTypeRef(C).first;
1830 assert(Type && "Missing type decl");
1831
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001832 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1833 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001834 }
1835
Daniel Dunbaracca7252009-11-30 20:42:49 +00001836 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001837 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001838 }
1839 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001840
1841 if (clang_isExpression(C.kind)) {
1842 Decl *D = getDeclFromExpr(getCursorExpr(C));
1843 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001844 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001845 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001846 }
1847
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001848 if (C.kind == CXCursor_MacroInstantiation)
1849 return createCXString(getCursorMacroInstantiation(C)->getName()
1850 ->getNameStart());
1851
Douglas Gregor572feb22010-03-18 18:04:21 +00001852 if (C.kind == CXCursor_MacroDefinition)
1853 return createCXString(getCursorMacroDefinition(C)->getName()
1854 ->getNameStart());
1855
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001856 if (clang_isDeclaration(C.kind))
1857 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001858
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001859 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001860}
1861
Ted Kremeneke68fff62010-02-17 00:41:32 +00001862CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001863 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001864 case CXCursor_FunctionDecl:
1865 return createCXString("FunctionDecl");
1866 case CXCursor_TypedefDecl:
1867 return createCXString("TypedefDecl");
1868 case CXCursor_EnumDecl:
1869 return createCXString("EnumDecl");
1870 case CXCursor_EnumConstantDecl:
1871 return createCXString("EnumConstantDecl");
1872 case CXCursor_StructDecl:
1873 return createCXString("StructDecl");
1874 case CXCursor_UnionDecl:
1875 return createCXString("UnionDecl");
1876 case CXCursor_ClassDecl:
1877 return createCXString("ClassDecl");
1878 case CXCursor_FieldDecl:
1879 return createCXString("FieldDecl");
1880 case CXCursor_VarDecl:
1881 return createCXString("VarDecl");
1882 case CXCursor_ParmDecl:
1883 return createCXString("ParmDecl");
1884 case CXCursor_ObjCInterfaceDecl:
1885 return createCXString("ObjCInterfaceDecl");
1886 case CXCursor_ObjCCategoryDecl:
1887 return createCXString("ObjCCategoryDecl");
1888 case CXCursor_ObjCProtocolDecl:
1889 return createCXString("ObjCProtocolDecl");
1890 case CXCursor_ObjCPropertyDecl:
1891 return createCXString("ObjCPropertyDecl");
1892 case CXCursor_ObjCIvarDecl:
1893 return createCXString("ObjCIvarDecl");
1894 case CXCursor_ObjCInstanceMethodDecl:
1895 return createCXString("ObjCInstanceMethodDecl");
1896 case CXCursor_ObjCClassMethodDecl:
1897 return createCXString("ObjCClassMethodDecl");
1898 case CXCursor_ObjCImplementationDecl:
1899 return createCXString("ObjCImplementationDecl");
1900 case CXCursor_ObjCCategoryImplDecl:
1901 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001902 case CXCursor_CXXMethod:
1903 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001904 case CXCursor_UnexposedDecl:
1905 return createCXString("UnexposedDecl");
1906 case CXCursor_ObjCSuperClassRef:
1907 return createCXString("ObjCSuperClassRef");
1908 case CXCursor_ObjCProtocolRef:
1909 return createCXString("ObjCProtocolRef");
1910 case CXCursor_ObjCClassRef:
1911 return createCXString("ObjCClassRef");
1912 case CXCursor_TypeRef:
1913 return createCXString("TypeRef");
1914 case CXCursor_UnexposedExpr:
1915 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001916 case CXCursor_BlockExpr:
1917 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001918 case CXCursor_DeclRefExpr:
1919 return createCXString("DeclRefExpr");
1920 case CXCursor_MemberRefExpr:
1921 return createCXString("MemberRefExpr");
1922 case CXCursor_CallExpr:
1923 return createCXString("CallExpr");
1924 case CXCursor_ObjCMessageExpr:
1925 return createCXString("ObjCMessageExpr");
1926 case CXCursor_UnexposedStmt:
1927 return createCXString("UnexposedStmt");
1928 case CXCursor_InvalidFile:
1929 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001930 case CXCursor_InvalidCode:
1931 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001932 case CXCursor_NoDeclFound:
1933 return createCXString("NoDeclFound");
1934 case CXCursor_NotImplemented:
1935 return createCXString("NotImplemented");
1936 case CXCursor_TranslationUnit:
1937 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001938 case CXCursor_UnexposedAttr:
1939 return createCXString("UnexposedAttr");
1940 case CXCursor_IBActionAttr:
1941 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001942 case CXCursor_IBOutletAttr:
1943 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00001944 case CXCursor_IBOutletCollectionAttr:
1945 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001946 case CXCursor_PreprocessingDirective:
1947 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001948 case CXCursor_MacroDefinition:
1949 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001950 case CXCursor_MacroInstantiation:
1951 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001952 case CXCursor_Namespace:
1953 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001954 case CXCursor_LinkageSpec:
1955 return createCXString("LinkageSpec");
Steve Naroff89922f82009-08-31 00:59:03 +00001956 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001957
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001958 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001959 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001960}
Steve Naroff89922f82009-08-31 00:59:03 +00001961
Ted Kremeneke68fff62010-02-17 00:41:32 +00001962enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1963 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001964 CXClientData client_data) {
1965 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1966 *BestCursor = cursor;
1967 return CXChildVisit_Recurse;
1968}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001969
Douglas Gregorb9790342010-01-22 21:44:22 +00001970CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1971 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001972 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001973
Douglas Gregorb9790342010-01-22 21:44:22 +00001974 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00001975 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1976
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001977 // Translate the given source location to make it point at the beginning of
1978 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00001979 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00001980
1981 // Guard against an invalid SourceLocation, or we may assert in one
1982 // of the following calls.
1983 if (SLoc.isInvalid())
1984 return clang_getNullCursor();
1985
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001986 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
1987 CXXUnit->getASTContext().getLangOptions());
1988
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001989 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1990 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001991 // FIXME: Would be great to have a "hint" cursor, then walk from that
1992 // hint cursor upward until we find a cursor whose source range encloses
1993 // the region of interest, rather than starting from the translation unit.
1994 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001995 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001996 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001997 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001998 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001999 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002000}
2001
Ted Kremenek73885552009-11-17 19:28:59 +00002002CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002003 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002004}
2005
2006unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002007 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002008}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002009
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002010unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002011 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2012}
2013
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002014unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002015 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2016}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002017
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002018unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002019 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2020}
2021
Douglas Gregor97b98722010-01-19 23:20:36 +00002022unsigned clang_isExpression(enum CXCursorKind K) {
2023 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2024}
2025
2026unsigned clang_isStatement(enum CXCursorKind K) {
2027 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2028}
2029
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002030unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2031 return K == CXCursor_TranslationUnit;
2032}
2033
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002034unsigned clang_isPreprocessing(enum CXCursorKind K) {
2035 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2036}
2037
Ted Kremenekad6eff62010-03-08 21:17:29 +00002038unsigned clang_isUnexposed(enum CXCursorKind K) {
2039 switch (K) {
2040 case CXCursor_UnexposedDecl:
2041 case CXCursor_UnexposedExpr:
2042 case CXCursor_UnexposedStmt:
2043 case CXCursor_UnexposedAttr:
2044 return true;
2045 default:
2046 return false;
2047 }
2048}
2049
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002050CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002051 return C.kind;
2052}
2053
Douglas Gregor98258af2010-01-18 22:46:11 +00002054CXSourceLocation clang_getCursorLocation(CXCursor C) {
2055 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002056 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002057 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002058 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2059 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002060 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002061 }
2062
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002063 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002064 std::pair<ObjCProtocolDecl *, SourceLocation> P
2065 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002066 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002067 }
2068
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002069 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002070 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2071 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002072 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002073 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002074
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002075 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002076 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002077 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002078 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002079
Douglas Gregorf46034a2010-01-18 23:41:10 +00002080 default:
2081 // FIXME: Need a way to enumerate all non-reference cases.
2082 llvm_unreachable("Missed a reference kind");
2083 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002084 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002085
2086 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002087 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002088 getLocationFromExpr(getCursorExpr(C)));
2089
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002090 if (C.kind == CXCursor_PreprocessingDirective) {
2091 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2092 return cxloc::translateSourceLocation(getCursorContext(C), L);
2093 }
Douglas Gregor48072312010-03-18 15:23:44 +00002094
2095 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002096 SourceLocation L
2097 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002098 return cxloc::translateSourceLocation(getCursorContext(C), L);
2099 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002100
2101 if (C.kind == CXCursor_MacroDefinition) {
2102 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2103 return cxloc::translateSourceLocation(getCursorContext(C), L);
2104 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002105
Ted Kremenek9a700d22010-05-12 06:16:13 +00002106 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002107 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002108
Douglas Gregorf46034a2010-01-18 23:41:10 +00002109 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002110 SourceLocation Loc = D->getLocation();
2111 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2112 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002113 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002114}
Douglas Gregora7bde202010-01-19 00:34:46 +00002115
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002116} // end extern "C"
2117
2118static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002119 if (clang_isReference(C.kind)) {
2120 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002121 case CXCursor_ObjCSuperClassRef:
2122 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002123
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002124 case CXCursor_ObjCProtocolRef:
2125 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002126
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002127 case CXCursor_ObjCClassRef:
2128 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002129
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002130 case CXCursor_TypeRef:
2131 return getCursorTypeRef(C).second;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002132
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002133 default:
2134 // FIXME: Need a way to enumerate all non-reference cases.
2135 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002136 }
2137 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002138
2139 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002140 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002141
2142 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002143 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002144
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002145 if (C.kind == CXCursor_PreprocessingDirective)
2146 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002147
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002148 if (C.kind == CXCursor_MacroInstantiation)
2149 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002150
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002151 if (C.kind == CXCursor_MacroDefinition)
2152 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002153
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002154 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2155 return getCursorDecl(C)->getSourceRange();
2156
2157 return SourceRange();
2158}
2159
2160extern "C" {
2161
2162CXSourceRange clang_getCursorExtent(CXCursor C) {
2163 SourceRange R = getRawCursorExtent(C);
2164 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002165 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002166
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002167 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002168}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002169
2170CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002171 if (clang_isInvalid(C.kind))
2172 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002173
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002174 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002175 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002176 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002177
Douglas Gregor97b98722010-01-19 23:20:36 +00002178 if (clang_isExpression(C.kind)) {
2179 Decl *D = getDeclFromExpr(getCursorExpr(C));
2180 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002181 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002182 return clang_getNullCursor();
2183 }
2184
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002185 if (C.kind == CXCursor_MacroInstantiation) {
2186 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2187 return MakeMacroDefinitionCursor(Def, CXXUnit);
2188 }
2189
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002190 if (!clang_isReference(C.kind))
2191 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002192
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002193 switch (C.kind) {
2194 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002195 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002196
2197 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002198 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002199
2200 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002201 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002202
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002203 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002204 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002205
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002206 default:
2207 // We would prefer to enumerate all non-reference cursor kinds here.
2208 llvm_unreachable("Unhandled reference cursor kind");
2209 break;
2210 }
2211 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002212
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002213 return clang_getNullCursor();
2214}
2215
Douglas Gregorb6998662010-01-19 19:34:47 +00002216CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002217 if (clang_isInvalid(C.kind))
2218 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002219
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002220 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002221
Douglas Gregorb6998662010-01-19 19:34:47 +00002222 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002223 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002224 C = clang_getCursorReferenced(C);
2225 WasReference = true;
2226 }
2227
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002228 if (C.kind == CXCursor_MacroInstantiation)
2229 return clang_getCursorReferenced(C);
2230
Douglas Gregorb6998662010-01-19 19:34:47 +00002231 if (!clang_isDeclaration(C.kind))
2232 return clang_getNullCursor();
2233
2234 Decl *D = getCursorDecl(C);
2235 if (!D)
2236 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002237
Douglas Gregorb6998662010-01-19 19:34:47 +00002238 switch (D->getKind()) {
2239 // Declaration kinds that don't really separate the notions of
2240 // declaration and definition.
2241 case Decl::Namespace:
2242 case Decl::Typedef:
2243 case Decl::TemplateTypeParm:
2244 case Decl::EnumConstant:
2245 case Decl::Field:
2246 case Decl::ObjCIvar:
2247 case Decl::ObjCAtDefsField:
2248 case Decl::ImplicitParam:
2249 case Decl::ParmVar:
2250 case Decl::NonTypeTemplateParm:
2251 case Decl::TemplateTemplateParm:
2252 case Decl::ObjCCategoryImpl:
2253 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002254 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002255 case Decl::LinkageSpec:
2256 case Decl::ObjCPropertyImpl:
2257 case Decl::FileScopeAsm:
2258 case Decl::StaticAssert:
2259 case Decl::Block:
2260 return C;
2261
2262 // Declaration kinds that don't make any sense here, but are
2263 // nonetheless harmless.
2264 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002265 break;
2266
2267 // Declaration kinds for which the definition is not resolvable.
2268 case Decl::UnresolvedUsingTypename:
2269 case Decl::UnresolvedUsingValue:
2270 break;
2271
2272 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002273 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2274 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002275
2276 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002277 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002278
2279 case Decl::Enum:
2280 case Decl::Record:
2281 case Decl::CXXRecord:
2282 case Decl::ClassTemplateSpecialization:
2283 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002284 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002285 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002286 return clang_getNullCursor();
2287
2288 case Decl::Function:
2289 case Decl::CXXMethod:
2290 case Decl::CXXConstructor:
2291 case Decl::CXXDestructor:
2292 case Decl::CXXConversion: {
2293 const FunctionDecl *Def = 0;
2294 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002295 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002296 return clang_getNullCursor();
2297 }
2298
2299 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002300 // Ask the variable if it has a definition.
2301 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2302 return MakeCXCursor(Def, CXXUnit);
2303 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002304 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002305
Douglas Gregorb6998662010-01-19 19:34:47 +00002306 case Decl::FunctionTemplate: {
2307 const FunctionDecl *Def = 0;
2308 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002309 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002310 return clang_getNullCursor();
2311 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002312
Douglas Gregorb6998662010-01-19 19:34:47 +00002313 case Decl::ClassTemplate: {
2314 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002315 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002316 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002317 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002318 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002319 return clang_getNullCursor();
2320 }
2321
2322 case Decl::Using: {
2323 UsingDecl *Using = cast<UsingDecl>(D);
2324 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002325 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2326 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002327 S != SEnd; ++S) {
2328 if (Def != clang_getNullCursor()) {
2329 // FIXME: We have no way to return multiple results.
2330 return clang_getNullCursor();
2331 }
2332
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002333 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002334 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002335 }
2336
2337 return Def;
2338 }
2339
2340 case Decl::UsingShadow:
2341 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002342 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002343 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002344
2345 case Decl::ObjCMethod: {
2346 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2347 if (Method->isThisDeclarationADefinition())
2348 return C;
2349
2350 // Dig out the method definition in the associated
2351 // @implementation, if we have it.
2352 // FIXME: The ASTs should make finding the definition easier.
2353 if (ObjCInterfaceDecl *Class
2354 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2355 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2356 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2357 Method->isInstanceMethod()))
2358 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002359 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002360
2361 return clang_getNullCursor();
2362 }
2363
2364 case Decl::ObjCCategory:
2365 if (ObjCCategoryImplDecl *Impl
2366 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002367 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002368 return clang_getNullCursor();
2369
2370 case Decl::ObjCProtocol:
2371 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2372 return C;
2373 return clang_getNullCursor();
2374
2375 case Decl::ObjCInterface:
2376 // There are two notions of a "definition" for an Objective-C
2377 // class: the interface and its implementation. When we resolved a
2378 // reference to an Objective-C class, produce the @interface as
2379 // the definition; when we were provided with the interface,
2380 // produce the @implementation as the definition.
2381 if (WasReference) {
2382 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2383 return C;
2384 } else if (ObjCImplementationDecl *Impl
2385 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002386 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002387 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002388
Douglas Gregorb6998662010-01-19 19:34:47 +00002389 case Decl::ObjCProperty:
2390 // FIXME: We don't really know where to find the
2391 // ObjCPropertyImplDecls that implement this property.
2392 return clang_getNullCursor();
2393
2394 case Decl::ObjCCompatibleAlias:
2395 if (ObjCInterfaceDecl *Class
2396 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2397 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002398 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002399
Douglas Gregorb6998662010-01-19 19:34:47 +00002400 return clang_getNullCursor();
2401
2402 case Decl::ObjCForwardProtocol: {
2403 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2404 if (Forward->protocol_size() == 1)
2405 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002406 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002407 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002408
2409 // FIXME: Cannot return multiple definitions.
2410 return clang_getNullCursor();
2411 }
2412
2413 case Decl::ObjCClass: {
2414 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2415 if (Class->size() == 1) {
2416 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2417 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002418 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002419 return clang_getNullCursor();
2420 }
2421
2422 // FIXME: Cannot return multiple definitions.
2423 return clang_getNullCursor();
2424 }
2425
2426 case Decl::Friend:
2427 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002428 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002429 return clang_getNullCursor();
2430
2431 case Decl::FriendTemplate:
2432 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002433 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002434 return clang_getNullCursor();
2435 }
2436
2437 return clang_getNullCursor();
2438}
2439
2440unsigned clang_isCursorDefinition(CXCursor C) {
2441 if (!clang_isDeclaration(C.kind))
2442 return 0;
2443
2444 return clang_getCursorDefinition(C) == C;
2445}
2446
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002447void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002448 const char **startBuf,
2449 const char **endBuf,
2450 unsigned *startLine,
2451 unsigned *startColumn,
2452 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002453 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002454 assert(getCursorDecl(C) && "CXCursor has null decl");
2455 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002456 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2457 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002458
Steve Naroff4ade6d62009-09-23 17:52:52 +00002459 SourceManager &SM = FD->getASTContext().getSourceManager();
2460 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2461 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2462 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2463 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2464 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2465 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2466}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002467
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002468void clang_enableStackTraces(void) {
2469 llvm::sys::PrintStackTraceOnErrorSignal();
2470}
2471
Ted Kremenekfb480492010-01-13 21:46:36 +00002472} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002473
Ted Kremenekfb480492010-01-13 21:46:36 +00002474//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002475// Token-based Operations.
2476//===----------------------------------------------------------------------===//
2477
2478/* CXToken layout:
2479 * int_data[0]: a CXTokenKind
2480 * int_data[1]: starting token location
2481 * int_data[2]: token length
2482 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002483 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002484 * otherwise unused.
2485 */
2486extern "C" {
2487
2488CXTokenKind clang_getTokenKind(CXToken CXTok) {
2489 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2490}
2491
2492CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2493 switch (clang_getTokenKind(CXTok)) {
2494 case CXToken_Identifier:
2495 case CXToken_Keyword:
2496 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002497 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2498 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002499
2500 case CXToken_Literal: {
2501 // We have stashed the starting pointer in the ptr_data field. Use it.
2502 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002503 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002504 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002505
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002506 case CXToken_Punctuation:
2507 case CXToken_Comment:
2508 break;
2509 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002510
2511 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002512 // deconstructing the source location.
2513 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2514 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002515 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002516
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002517 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2518 std::pair<FileID, unsigned> LocInfo
2519 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002520 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002521 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002522 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2523 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002524 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002525
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002526 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002527}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002528
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002529CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2530 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2531 if (!CXXUnit)
2532 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002533
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002534 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2535 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2536}
2537
2538CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2539 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002540 if (!CXXUnit)
2541 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002542
2543 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002544 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2545}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002546
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002547void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2548 CXToken **Tokens, unsigned *NumTokens) {
2549 if (Tokens)
2550 *Tokens = 0;
2551 if (NumTokens)
2552 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002553
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002554 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2555 if (!CXXUnit || !Tokens || !NumTokens)
2556 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002557
Douglas Gregorbdf60622010-03-05 21:16:25 +00002558 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2559
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002560 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002561 if (R.isInvalid())
2562 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002563
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002564 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2565 std::pair<FileID, unsigned> BeginLocInfo
2566 = SourceMgr.getDecomposedLoc(R.getBegin());
2567 std::pair<FileID, unsigned> EndLocInfo
2568 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002569
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002570 // Cannot tokenize across files.
2571 if (BeginLocInfo.first != EndLocInfo.first)
2572 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002573
2574 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002575 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002576 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002577 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002578 if (Invalid)
2579 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002580
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002581 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2582 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002583 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002584 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002585
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002586 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002587 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002588 llvm::SmallVector<CXToken, 32> CXTokens;
2589 Token Tok;
2590 do {
2591 // Lex the next token
2592 Lex.LexFromRawLexer(Tok);
2593 if (Tok.is(tok::eof))
2594 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002595
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002596 // Initialize the CXToken.
2597 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002598
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002599 // - Common fields
2600 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2601 CXTok.int_data[2] = Tok.getLength();
2602 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002603
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002604 // - Kind-specific fields
2605 if (Tok.isLiteral()) {
2606 CXTok.int_data[0] = CXToken_Literal;
2607 CXTok.ptr_data = (void *)Tok.getLiteralData();
2608 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002609 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002610 std::pair<FileID, unsigned> LocInfo
2611 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002612 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002613 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002614 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2615 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002616 return;
2617
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002618 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002619 IdentifierInfo *II
2620 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002621
2622 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2623 CXTok.int_data[0] = CXToken_Keyword;
2624 }
2625 else {
2626 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2627 CXToken_Identifier
2628 : CXToken_Keyword;
2629 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002630 CXTok.ptr_data = II;
2631 } else if (Tok.is(tok::comment)) {
2632 CXTok.int_data[0] = CXToken_Comment;
2633 CXTok.ptr_data = 0;
2634 } else {
2635 CXTok.int_data[0] = CXToken_Punctuation;
2636 CXTok.ptr_data = 0;
2637 }
2638 CXTokens.push_back(CXTok);
2639 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002640
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002641 if (CXTokens.empty())
2642 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002643
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002644 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2645 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2646 *NumTokens = CXTokens.size();
2647}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002648
Ted Kremenek6db61092010-05-05 00:55:15 +00002649void clang_disposeTokens(CXTranslationUnit TU,
2650 CXToken *Tokens, unsigned NumTokens) {
2651 free(Tokens);
2652}
2653
2654} // end: extern "C"
2655
2656//===----------------------------------------------------------------------===//
2657// Token annotation APIs.
2658//===----------------------------------------------------------------------===//
2659
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002660typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002661static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2662 CXCursor parent,
2663 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002664namespace {
2665class AnnotateTokensWorker {
2666 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002667 CXToken *Tokens;
2668 CXCursor *Cursors;
2669 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002670 unsigned TokIdx;
2671 CursorVisitor AnnotateVis;
2672 SourceManager &SrcMgr;
2673
2674 bool MoreTokens() const { return TokIdx < NumTokens; }
2675 unsigned NextToken() const { return TokIdx; }
2676 void AdvanceToken() { ++TokIdx; }
2677 SourceLocation GetTokenLoc(unsigned tokI) {
2678 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2679 }
2680
Ted Kremenek6db61092010-05-05 00:55:15 +00002681public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002682 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002683 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2684 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002685 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002686 NumTokens(numTokens), TokIdx(0),
2687 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2688 Decl::MaxPCHLevel, RegionOfInterest),
2689 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002690
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002691 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002692 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002693 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002694};
2695}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002696
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002697void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2698 // Walk the AST within the region of interest, annotating tokens
2699 // along the way.
2700 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002701
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002702 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2703 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2704 if (Pos != Annotated.end())
2705 Cursors[I] = Pos->second;
2706 }
2707
2708 // Finish up annotating any tokens left.
2709 if (!MoreTokens())
2710 return;
2711
2712 const CXCursor &C = clang_getNullCursor();
2713 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2714 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2715 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002716 }
2717}
2718
Ted Kremenek6db61092010-05-05 00:55:15 +00002719enum CXChildVisitResult
2720AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002721 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2722 // We can always annotate a preprocessing directive/macro instantiation.
2723 if (clang_isPreprocessing(cursor.kind)) {
2724 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002725 return CXChildVisit_Recurse;
2726 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002727
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002728 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00002729
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002730 if (cursorRange.isInvalid())
2731 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002732
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002733 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2734
Ted Kremeneka333c662010-05-12 05:29:33 +00002735 // Adjust the annotated range based specific declarations.
2736 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2737 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002738 Decl *D = cxcursor::getCursorDecl(cursor);
2739 // Don't visit synthesized ObjC methods, since they have no syntatic
2740 // representation in the source.
2741 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2742 if (MD->isSynthesized())
2743 return CXChildVisit_Continue;
2744 }
2745 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002746 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2747 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002748 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002749 if (TLoc.isValid() &&
2750 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002751 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002752 }
2753 }
2754 }
2755
Ted Kremenek3f404602010-08-14 01:14:06 +00002756 // If the location of the cursor occurs within a macro instantiation, record
2757 // the spelling location of the cursor in our annotation map. We can then
2758 // paper over the token labelings during a post-processing step to try and
2759 // get cursor mappings for tokens that are the *arguments* of a macro
2760 // instantiation.
2761 if (L.isMacroID()) {
2762 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
2763 // Only invalidate the old annotation if it isn't part of a preprocessing
2764 // directive. Here we assume that the default construction of CXCursor
2765 // results in CXCursor.kind being an initialized value (i.e., 0). If
2766 // this isn't the case, we can fix by doing lookup + insertion.
2767
2768 CXCursor &oldC = Annotated[rawEncoding];
2769 if (!clang_isPreprocessing(oldC.kind))
2770 oldC = cursor;
2771 }
2772
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002773 const enum CXCursorKind K = clang_getCursorKind(parent);
2774 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00002775 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
2776 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002777
2778 while (MoreTokens()) {
2779 const unsigned I = NextToken();
2780 SourceLocation TokLoc = GetTokenLoc(I);
2781 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2782 case RangeBefore:
2783 Cursors[I] = updateC;
2784 AdvanceToken();
2785 continue;
2786 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002787 case RangeOverlap:
2788 break;
2789 }
2790 break;
2791 }
2792
2793 // Visit children to get their cursor information.
2794 const unsigned BeforeChildren = NextToken();
2795 VisitChildren(cursor);
2796 const unsigned AfterChildren = NextToken();
2797
2798 // Adjust 'Last' to the last token within the extent of the cursor.
2799 while (MoreTokens()) {
2800 const unsigned I = NextToken();
2801 SourceLocation TokLoc = GetTokenLoc(I);
2802 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2803 case RangeBefore:
2804 assert(0 && "Infeasible");
2805 case RangeAfter:
2806 break;
2807 case RangeOverlap:
2808 Cursors[I] = updateC;
2809 AdvanceToken();
2810 continue;
2811 }
2812 break;
2813 }
2814 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002815
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002816 // Scan the tokens that are at the beginning of the cursor, but are not
2817 // capture by the child cursors.
2818
2819 // For AST elements within macros, rely on a post-annotate pass to
2820 // to correctly annotate the tokens with cursors. Otherwise we can
2821 // get confusing results of having tokens that map to cursors that really
2822 // are expanded by an instantiation.
2823 if (L.isMacroID())
2824 cursor = clang_getNullCursor();
2825
2826 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2827 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2828 break;
2829 Cursors[I] = cursor;
2830 }
2831 // Scan the tokens that are at the end of the cursor, but are not captured
2832 // but the child cursors.
2833 for (unsigned I = AfterChildren; I != Last; ++I)
2834 Cursors[I] = cursor;
2835
2836 TokIdx = Last;
2837 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002838}
2839
Ted Kremenek6db61092010-05-05 00:55:15 +00002840static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2841 CXCursor parent,
2842 CXClientData client_data) {
2843 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2844}
2845
2846extern "C" {
2847
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002848void clang_annotateTokens(CXTranslationUnit TU,
2849 CXToken *Tokens, unsigned NumTokens,
2850 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002851
2852 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002853 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002854
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002855 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002856 if (!CXXUnit) {
2857 // Any token we don't specifically annotate will have a NULL cursor.
2858 const CXCursor &C = clang_getNullCursor();
2859 for (unsigned I = 0; I != NumTokens; ++I)
2860 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002861 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002862 }
2863
Douglas Gregorbdf60622010-03-05 21:16:25 +00002864 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002865
Douglas Gregor0396f462010-03-19 05:22:59 +00002866 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002867 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002868 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2869 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002870 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
2871 clang_getTokenLocation(TU,
2872 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002873
Douglas Gregor0396f462010-03-19 05:22:59 +00002874 // A mapping from the source locations found when re-lexing or traversing the
2875 // region of interest to the corresponding cursors.
2876 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002877
2878 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002879 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002880 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2881 std::pair<FileID, unsigned> BeginLocInfo
2882 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2883 std::pair<FileID, unsigned> EndLocInfo
2884 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002885
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002886 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002887 bool Invalid = false;
2888 if (BeginLocInfo.first == EndLocInfo.first &&
2889 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2890 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002891 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2892 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002893 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002894 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002895 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002896
2897 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002898 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002899 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002900 Token Tok;
2901 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002902
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002903 reprocess:
2904 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2905 // We have found a preprocessing directive. Gobble it up so that we
2906 // don't see it while preprocessing these tokens later, but keep track of
2907 // all of the token locations inside this preprocessing directive so that
2908 // we can annotate them appropriately.
2909 //
2910 // FIXME: Some simple tests here could identify macro definitions and
2911 // #undefs, to provide specific cursor kinds for those.
2912 std::vector<SourceLocation> Locations;
2913 do {
2914 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002915 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002916 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002917
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002918 using namespace cxcursor;
2919 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002920 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2921 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002922 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002923 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2924 Annotated[Locations[I].getRawEncoding()] = Cursor;
2925 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002926
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002927 if (Tok.isAtStartOfLine())
2928 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002929
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002930 continue;
2931 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002932
Douglas Gregor48072312010-03-18 15:23:44 +00002933 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002934 break;
2935 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002936 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002937
Douglas Gregor0396f462010-03-19 05:22:59 +00002938 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002939 // a specific cursor.
2940 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2941 CXXUnit, RegionOfInterest);
2942 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002943}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002944} // end: extern "C"
2945
2946//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002947// Operations for querying linkage of a cursor.
2948//===----------------------------------------------------------------------===//
2949
2950extern "C" {
2951CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002952 if (!clang_isDeclaration(cursor.kind))
2953 return CXLinkage_Invalid;
2954
Ted Kremenek16b42592010-03-03 06:36:57 +00002955 Decl *D = cxcursor::getCursorDecl(cursor);
2956 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2957 switch (ND->getLinkage()) {
2958 case NoLinkage: return CXLinkage_NoLinkage;
2959 case InternalLinkage: return CXLinkage_Internal;
2960 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2961 case ExternalLinkage: return CXLinkage_External;
2962 };
2963
2964 return CXLinkage_Invalid;
2965}
2966} // end: extern "C"
2967
2968//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002969// Operations for querying language of a cursor.
2970//===----------------------------------------------------------------------===//
2971
2972static CXLanguageKind getDeclLanguage(const Decl *D) {
2973 switch (D->getKind()) {
2974 default:
2975 break;
2976 case Decl::ImplicitParam:
2977 case Decl::ObjCAtDefsField:
2978 case Decl::ObjCCategory:
2979 case Decl::ObjCCategoryImpl:
2980 case Decl::ObjCClass:
2981 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00002982 case Decl::ObjCForwardProtocol:
2983 case Decl::ObjCImplementation:
2984 case Decl::ObjCInterface:
2985 case Decl::ObjCIvar:
2986 case Decl::ObjCMethod:
2987 case Decl::ObjCProperty:
2988 case Decl::ObjCPropertyImpl:
2989 case Decl::ObjCProtocol:
2990 return CXLanguage_ObjC;
2991 case Decl::CXXConstructor:
2992 case Decl::CXXConversion:
2993 case Decl::CXXDestructor:
2994 case Decl::CXXMethod:
2995 case Decl::CXXRecord:
2996 case Decl::ClassTemplate:
2997 case Decl::ClassTemplatePartialSpecialization:
2998 case Decl::ClassTemplateSpecialization:
2999 case Decl::Friend:
3000 case Decl::FriendTemplate:
3001 case Decl::FunctionTemplate:
3002 case Decl::LinkageSpec:
3003 case Decl::Namespace:
3004 case Decl::NamespaceAlias:
3005 case Decl::NonTypeTemplateParm:
3006 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003007 case Decl::TemplateTemplateParm:
3008 case Decl::TemplateTypeParm:
3009 case Decl::UnresolvedUsingTypename:
3010 case Decl::UnresolvedUsingValue:
3011 case Decl::Using:
3012 case Decl::UsingDirective:
3013 case Decl::UsingShadow:
3014 return CXLanguage_CPlusPlus;
3015 }
3016
3017 return CXLanguage_C;
3018}
3019
3020extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003021
3022enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3023 if (clang_isDeclaration(cursor.kind))
3024 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3025 if (D->hasAttr<UnavailableAttr>() ||
3026 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3027 return CXAvailability_Available;
3028
3029 if (D->hasAttr<DeprecatedAttr>())
3030 return CXAvailability_Deprecated;
3031 }
3032
3033 return CXAvailability_Available;
3034}
3035
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003036CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3037 if (clang_isDeclaration(cursor.kind))
3038 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3039
3040 return CXLanguage_Invalid;
3041}
3042} // end: extern "C"
3043
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003044
3045//===----------------------------------------------------------------------===//
3046// C++ AST instrospection.
3047//===----------------------------------------------------------------------===//
3048
3049extern "C" {
3050unsigned clang_CXXMethod_isStatic(CXCursor C) {
3051 if (!clang_isDeclaration(C.kind))
3052 return 0;
3053 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
3054 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003055}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003056
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003057} // end: extern "C"
3058
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003059//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003060// Attribute introspection.
3061//===----------------------------------------------------------------------===//
3062
3063extern "C" {
3064CXType clang_getIBOutletCollectionType(CXCursor C) {
3065 if (C.kind != CXCursor_IBOutletCollectionAttr)
3066 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3067
3068 IBOutletCollectionAttr *A =
3069 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3070
3071 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3072}
3073} // end: extern "C"
3074
3075//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003076// CXString Operations.
3077//===----------------------------------------------------------------------===//
3078
3079extern "C" {
3080const char *clang_getCString(CXString string) {
3081 return string.Spelling;
3082}
3083
3084void clang_disposeString(CXString string) {
3085 if (string.MustFreeString && string.Spelling)
3086 free((void*)string.Spelling);
3087}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003088
Ted Kremenekfb480492010-01-13 21:46:36 +00003089} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003090
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003091namespace clang { namespace cxstring {
3092CXString createCXString(const char *String, bool DupString){
3093 CXString Str;
3094 if (DupString) {
3095 Str.Spelling = strdup(String);
3096 Str.MustFreeString = 1;
3097 } else {
3098 Str.Spelling = String;
3099 Str.MustFreeString = 0;
3100 }
3101 return Str;
3102}
3103
3104CXString createCXString(llvm::StringRef String, bool DupString) {
3105 CXString Result;
3106 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3107 char *Spelling = (char *)malloc(String.size() + 1);
3108 memmove(Spelling, String.data(), String.size());
3109 Spelling[String.size()] = 0;
3110 Result.Spelling = Spelling;
3111 Result.MustFreeString = 1;
3112 } else {
3113 Result.Spelling = String.data();
3114 Result.MustFreeString = 0;
3115 }
3116 return Result;
3117}
3118}}
3119
Ted Kremenek04bb7162010-01-22 22:44:15 +00003120//===----------------------------------------------------------------------===//
3121// Misc. utility functions.
3122//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003123
Ted Kremenek04bb7162010-01-22 22:44:15 +00003124extern "C" {
3125
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003126CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003127 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003128}
3129
3130} // end: extern "C"