blob: 2361f421a4b92a4514d697c919b97f5e35e15817 [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);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000288 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000289 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000290 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
291 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000292 bool VisitTagDecl(TagDecl *D);
293 bool VisitEnumConstantDecl(EnumConstantDecl *D);
294 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
295 bool VisitFunctionDecl(FunctionDecl *ND);
296 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000297 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000298 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
299 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
300 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
301 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000302 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000303 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
304 bool VisitObjCImplDecl(ObjCImplDecl *D);
305 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
306 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
307 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
308 // etc.
309 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
310 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
311 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000312 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000313 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000314
315 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000316 // FIXME: QualifiedTypeLoc doesn't provide any location information
317 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000318 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000319 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
320 bool VisitTagTypeLoc(TagTypeLoc TL);
321 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
322 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000323 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000324 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
325 bool VisitPointerTypeLoc(PointerTypeLoc TL);
326 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
327 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
328 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
329 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
330 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
331 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000332 // FIXME: Implement for TemplateSpecializationTypeLoc
333 // FIXME: Implement visitors here when the unimplemented TypeLocs get
334 // implemented
335 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
336 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000337
Douglas Gregora59e3902010-01-21 23:27:09 +0000338 // Statement visitors
339 bool VisitStmt(Stmt *S);
340 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000341 // FIXME: LabelStmt label?
342 bool VisitIfStmt(IfStmt *S);
343 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000344 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000345 bool VisitWhileStmt(WhileStmt *S);
346 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000347// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000348
Douglas Gregor336fd812010-01-23 00:40:08 +0000349 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000350 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
351 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000352 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000353 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000354 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000355 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000356 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000357 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000358 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000359 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000360 // FIXME: AddrLabelExpr (once we have cursors for labels)
361 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
362 bool VisitVAArgExpr(VAArgExpr *E);
363 // FIXME: InitListExpr (for the designators)
364 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000365};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000366
Ted Kremenekab188932010-01-05 19:32:54 +0000367} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000368
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000369static SourceRange getRawCursorExtent(CXCursor C);
370
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000371RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000372 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
373}
374
Douglas Gregorb1373d02010-01-20 20:59:29 +0000375/// \brief Visit the given cursor and, if requested by the visitor,
376/// its children.
377///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000378/// \param Cursor the cursor to visit.
379///
380/// \param CheckRegionOfInterest if true, then the caller already checked that
381/// this cursor is within the region of interest.
382///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000383/// \returns true if the visitation should be aborted, false if it
384/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000386 if (clang_isInvalid(Cursor.kind))
387 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000388
Douglas Gregorb1373d02010-01-20 20:59:29 +0000389 if (clang_isDeclaration(Cursor.kind)) {
390 Decl *D = getCursorDecl(Cursor);
391 assert(D && "Invalid declaration cursor");
392 if (D->getPCHLevel() > MaxPCHLevel)
393 return false;
394
395 if (D->isImplicit())
396 return false;
397 }
398
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000399 // If we have a range of interest, and this cursor doesn't intersect with it,
400 // we're done.
401 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000402 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000403 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000404 return false;
405 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000406
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407 switch (Visitor(Cursor, Parent, ClientData)) {
408 case CXChildVisit_Break:
409 return true;
410
411 case CXChildVisit_Continue:
412 return false;
413
414 case CXChildVisit_Recurse:
415 return VisitChildren(Cursor);
416 }
417
Douglas Gregorfd643772010-01-25 16:45:46 +0000418 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000419}
420
Douglas Gregor788f5a12010-03-20 00:41:21 +0000421std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
422CursorVisitor::getPreprocessedEntities() {
423 PreprocessingRecord &PPRec
424 = *TU->getPreprocessor().getPreprocessingRecord();
425
426 bool OnlyLocalDecls
427 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
428
429 // There is no region of interest; we have to walk everything.
430 if (RegionOfInterest.isInvalid())
431 return std::make_pair(PPRec.begin(OnlyLocalDecls),
432 PPRec.end(OnlyLocalDecls));
433
434 // Find the file in which the region of interest lands.
435 SourceManager &SM = TU->getSourceManager();
436 std::pair<FileID, unsigned> Begin
437 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
438 std::pair<FileID, unsigned> End
439 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
440
441 // The region of interest spans files; we have to walk everything.
442 if (Begin.first != End.first)
443 return std::make_pair(PPRec.begin(OnlyLocalDecls),
444 PPRec.end(OnlyLocalDecls));
445
446 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
447 = TU->getPreprocessedEntitiesByFile();
448 if (ByFileMap.empty()) {
449 // Build the mapping from files to sets of preprocessed entities.
450 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
451 EEnd = PPRec.end(OnlyLocalDecls);
452 E != EEnd; ++E) {
453 std::pair<FileID, unsigned> P
454 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
455 ByFileMap[P.first].push_back(*E);
456 }
457 }
458
459 return std::make_pair(ByFileMap[Begin.first].begin(),
460 ByFileMap[Begin.first].end());
461}
462
Douglas Gregorb1373d02010-01-20 20:59:29 +0000463/// \brief Visit the children of the given cursor.
464///
465/// \returns true if the visitation should be aborted, false if it
466/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000467bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000468 if (clang_isReference(Cursor.kind)) {
469 // By definition, references have no children.
470 return false;
471 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000472
473 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000474 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000475 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000476
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477 if (clang_isDeclaration(Cursor.kind)) {
478 Decl *D = getCursorDecl(Cursor);
479 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000480 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000481 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000482
Douglas Gregora59e3902010-01-21 23:27:09 +0000483 if (clang_isStatement(Cursor.kind))
484 return Visit(getCursorStmt(Cursor));
485 if (clang_isExpression(Cursor.kind))
486 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000487
Douglas Gregorb1373d02010-01-20 20:59:29 +0000488 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000489 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000490 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
491 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000492 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
493 TLEnd = CXXUnit->top_level_end();
494 TL != TLEnd; ++TL) {
495 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000496 return true;
497 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000498 } else if (VisitDeclContext(
499 CXXUnit->getASTContext().getTranslationUnitDecl()))
500 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000501
Douglas Gregor0396f462010-03-19 05:22:59 +0000502 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000503 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000504 // FIXME: Once we have the ability to deserialize a preprocessing record,
505 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000506 PreprocessingRecord::iterator E, EEnd;
507 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
509 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
510 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000511
Douglas Gregor0396f462010-03-19 05:22:59 +0000512 continue;
513 }
514
515 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
516 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
517 return true;
518
519 continue;
520 }
521 }
522 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000523 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000525
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000527 return false;
528}
529
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000530bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000531 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
532 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000533
Ted Kremenek664cffd2010-07-22 11:30:19 +0000534 if (Stmt *Body = B->getBody())
535 return Visit(MakeCXCursor(Body, StmtParent, TU));
536
537 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000538}
539
Douglas Gregorb1373d02010-01-20 20:59:29 +0000540bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000541 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000542 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000543
Ted Kremenek23173d72010-05-18 21:09:07 +0000544 Decl *D = *I;
545 if (D->getLexicalDeclContext() != DC)
546 continue;
547
548 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000549
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000550 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000551 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000552 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000553 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000554
555 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000556 case RangeBefore:
557 // This declaration comes before the region of interest; skip it.
558 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000559
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000560 case RangeAfter:
561 // This declaration comes after the region of interest; we're done.
562 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000563
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000564 case RangeOverlap:
565 // This declaration overlaps the region of interest; visit it.
566 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000567 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000568 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000569
Daniel Dunbard52864b2010-02-14 10:02:57 +0000570 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000571 return true;
572 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000573
Douglas Gregorb1373d02010-01-20 20:59:29 +0000574 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000575}
576
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000577bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
578 llvm_unreachable("Translation units are visited directly by Visit()");
579 return false;
580}
581
582bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
583 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
584 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000585
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000586 return false;
587}
588
589bool CursorVisitor::VisitTagDecl(TagDecl *D) {
590 return VisitDeclContext(D);
591}
592
593bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
594 if (Expr *Init = D->getInitExpr())
595 return Visit(MakeCXCursor(Init, StmtParent, TU));
596 return false;
597}
598
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000599bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
600 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
601 if (Visit(TSInfo->getTypeLoc()))
602 return true;
603
604 return false;
605}
606
Douglas Gregorb1373d02010-01-20 20:59:29 +0000607bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000608 if (VisitDeclaratorDecl(ND))
609 return true;
610
Douglas Gregora59e3902010-01-21 23:27:09 +0000611 if (ND->isThisDeclarationADefinition() &&
612 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
613 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000614
Douglas Gregorb1373d02010-01-20 20:59:29 +0000615 return false;
616}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000617
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000618bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
619 if (VisitDeclaratorDecl(D))
620 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000621
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000622 if (Expr *BitWidth = D->getBitWidth())
623 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000624
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000625 return false;
626}
627
628bool CursorVisitor::VisitVarDecl(VarDecl *D) {
629 if (VisitDeclaratorDecl(D))
630 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000631
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000632 if (Expr *Init = D->getInit())
633 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000634
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000635 return false;
636}
637
638bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000639 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
640 if (Visit(TSInfo->getTypeLoc()))
641 return true;
642
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000643 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000644 PEnd = ND->param_end();
645 P != PEnd; ++P) {
646 if (Visit(MakeCXCursor(*P, TU)))
647 return true;
648 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000649
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000650 if (ND->isThisDeclarationADefinition() &&
651 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
652 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000653
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000654 return false;
655}
656
Douglas Gregora59e3902010-01-21 23:27:09 +0000657bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
658 return VisitDeclContext(D);
659}
660
Douglas Gregorb1373d02010-01-20 20:59:29 +0000661bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000662 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
663 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000664 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000665
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000666 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
667 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
668 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000669 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000670 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000671
Douglas Gregora59e3902010-01-21 23:27:09 +0000672 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000673}
674
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000675bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
676 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
677 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
678 E = PID->protocol_end(); I != E; ++I, ++PL)
679 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
680 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000681
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000682 return VisitObjCContainerDecl(PID);
683}
684
Ted Kremenek23173d72010-05-18 21:09:07 +0000685bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000686 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
687 return true;
688
Ted Kremenek23173d72010-05-18 21:09:07 +0000689 // FIXME: This implements a workaround with @property declarations also being
690 // installed in the DeclContext for the @interface. Eventually this code
691 // should be removed.
692 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
693 if (!CDecl || !CDecl->IsClassExtension())
694 return false;
695
696 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
697 if (!ID)
698 return false;
699
700 IdentifierInfo *PropertyId = PD->getIdentifier();
701 ObjCPropertyDecl *prevDecl =
702 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
703
704 if (!prevDecl)
705 return false;
706
707 // Visit synthesized methods since they will be skipped when visiting
708 // the @interface.
709 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
710 if (MD->isSynthesized())
711 if (Visit(MakeCXCursor(MD, TU)))
712 return true;
713
714 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
715 if (MD->isSynthesized())
716 if (Visit(MakeCXCursor(MD, TU)))
717 return true;
718
719 return false;
720}
721
Douglas Gregorb1373d02010-01-20 20:59:29 +0000722bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000723 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000724 if (D->getSuperClass() &&
725 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000726 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000727 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000728 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000729
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000730 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
731 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
732 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000733 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000734 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000735
Douglas Gregora59e3902010-01-21 23:27:09 +0000736 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000737}
738
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000739bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
740 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000741}
742
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000743bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000744 // 'ID' could be null when dealing with invalid code.
745 if (ObjCInterfaceDecl *ID = D->getClassInterface())
746 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
747 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000748
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000749 return VisitObjCImplDecl(D);
750}
751
752bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
753#if 0
754 // Issue callbacks for super class.
755 // FIXME: No source location information!
756 if (D->getSuperClass() &&
757 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000758 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000759 TU)))
760 return true;
761#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000762
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000763 return VisitObjCImplDecl(D);
764}
765
766bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
767 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
768 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
769 E = D->protocol_end();
770 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000771 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000772 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000773
774 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000775}
776
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000777bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
778 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
779 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
780 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000781
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000782 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000783}
784
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000785bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
786 return VisitDeclContext(D);
787}
788
Ted Kremeneka0536d82010-05-07 01:04:29 +0000789bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
790 return VisitDeclContext(D);
791}
792
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000793bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
794 ASTContext &Context = TU->getASTContext();
795
796 // Some builtin types (such as Objective-C's "id", "sel", and
797 // "Class") have associated declarations. Create cursors for those.
798 QualType VisitType;
799 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000800 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000801 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000802 case BuiltinType::Char_U:
803 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000804 case BuiltinType::Char16:
805 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000806 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000807 case BuiltinType::UInt:
808 case BuiltinType::ULong:
809 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000810 case BuiltinType::UInt128:
811 case BuiltinType::Char_S:
812 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000813 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000814 case BuiltinType::Short:
815 case BuiltinType::Int:
816 case BuiltinType::Long:
817 case BuiltinType::LongLong:
818 case BuiltinType::Int128:
819 case BuiltinType::Float:
820 case BuiltinType::Double:
821 case BuiltinType::LongDouble:
822 case BuiltinType::NullPtr:
823 case BuiltinType::Overload:
824 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000825 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000826
827 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000828 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000829
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000830 case BuiltinType::ObjCId:
831 VisitType = Context.getObjCIdType();
832 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000833
834 case BuiltinType::ObjCClass:
835 VisitType = Context.getObjCClassType();
836 break;
837
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000838 case BuiltinType::ObjCSel:
839 VisitType = Context.getObjCSelType();
840 break;
841 }
842
843 if (!VisitType.isNull()) {
844 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000845 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000846 TU));
847 }
848
849 return false;
850}
851
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000852bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
853 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
854}
855
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000856bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
857 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
858}
859
860bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
861 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
862}
863
864bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
865 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
866 return true;
867
John McCallc12c5bb2010-05-15 11:32:37 +0000868 return false;
869}
870
871bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
872 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
873 return true;
874
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000875 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
876 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
877 TU)))
878 return true;
879 }
880
881 return false;
882}
883
884bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +0000885 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000886}
887
888bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
889 return Visit(TL.getPointeeLoc());
890}
891
892bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
893 return Visit(TL.getPointeeLoc());
894}
895
896bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
897 return Visit(TL.getPointeeLoc());
898}
899
900bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000901 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000902}
903
904bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000905 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000906}
907
908bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
909 if (Visit(TL.getResultLoc()))
910 return true;
911
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000912 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000913 if (Decl *D = TL.getArg(I))
914 if (Visit(MakeCXCursor(D, TU)))
915 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000916
917 return false;
918}
919
920bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
921 if (Visit(TL.getElementLoc()))
922 return true;
923
924 if (Expr *Size = TL.getSizeExpr())
925 return Visit(MakeCXCursor(Size, StmtParent, TU));
926
927 return false;
928}
929
Douglas Gregor2332c112010-01-21 20:48:56 +0000930bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
931 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
932}
933
934bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
935 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
936 return Visit(TSInfo->getTypeLoc());
937
938 return false;
939}
940
Douglas Gregora59e3902010-01-21 23:27:09 +0000941bool CursorVisitor::VisitStmt(Stmt *S) {
942 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
943 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000944 if (Stmt *C = *Child)
945 if (Visit(MakeCXCursor(C, StmtParent, TU)))
946 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +0000947 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000948
Douglas Gregora59e3902010-01-21 23:27:09 +0000949 return false;
950}
951
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000952bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
953 // Specially handle CaseStmts because they can be nested, e.g.:
954 //
955 // case 1:
956 // case 2:
957 //
958 // In this case the second CaseStmt is the child of the first. Walking
959 // these recursively can blow out the stack.
960 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
961 while (true) {
962 // Set the Parent field to Cursor, then back to its old value once we're
963 // done.
964 SetParentRAII SetParent(Parent, StmtParent, Cursor);
965
966 if (Stmt *LHS = S->getLHS())
967 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
968 return true;
969 if (Stmt *RHS = S->getRHS())
970 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
971 return true;
972 if (Stmt *SubStmt = S->getSubStmt()) {
973 if (!isa<CaseStmt>(SubStmt))
974 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
975
976 // Specially handle 'CaseStmt' so that we don't blow out the stack.
977 CaseStmt *CS = cast<CaseStmt>(SubStmt);
978 Cursor = MakeCXCursor(CS, StmtParent, TU);
979 if (RegionOfInterest.isValid()) {
980 SourceRange Range = CS->getSourceRange();
981 if (Range.isInvalid() || CompareRegionOfInterest(Range))
982 return false;
983 }
984
985 switch (Visitor(Cursor, Parent, ClientData)) {
986 case CXChildVisit_Break: return true;
987 case CXChildVisit_Continue: return false;
988 case CXChildVisit_Recurse:
989 // Perform tail-recursion manually.
990 S = CS;
991 continue;
992 }
993 }
994 return false;
995 }
996}
997
Douglas Gregora59e3902010-01-21 23:27:09 +0000998bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
999 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1000 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001001 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001002 return true;
1003 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001004
Douglas Gregora59e3902010-01-21 23:27:09 +00001005 return false;
1006}
1007
Douglas Gregorf5bab412010-01-22 01:00:11 +00001008bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1009 if (VarDecl *Var = S->getConditionVariable()) {
1010 if (Visit(MakeCXCursor(Var, TU)))
1011 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012 }
1013
Douglas Gregor263b47b2010-01-25 16:12:32 +00001014 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1015 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001016 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1017 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001018 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1019 return true;
1020
1021 return false;
1022}
1023
1024bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1025 if (VarDecl *Var = S->getConditionVariable()) {
1026 if (Visit(MakeCXCursor(Var, TU)))
1027 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028 }
1029
Douglas Gregor263b47b2010-01-25 16:12:32 +00001030 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1031 return true;
1032 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1033 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001034
Douglas Gregor263b47b2010-01-25 16:12:32 +00001035 return false;
1036}
1037
1038bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1039 if (VarDecl *Var = S->getConditionVariable()) {
1040 if (Visit(MakeCXCursor(Var, TU)))
1041 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001042 }
1043
Douglas Gregor263b47b2010-01-25 16:12:32 +00001044 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1045 return true;
1046 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001047 return true;
1048
Douglas Gregor263b47b2010-01-25 16:12:32 +00001049 return false;
1050}
1051
1052bool CursorVisitor::VisitForStmt(ForStmt *S) {
1053 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1054 return true;
1055 if (VarDecl *Var = S->getConditionVariable()) {
1056 if (Visit(MakeCXCursor(Var, TU)))
1057 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001058 }
1059
Douglas Gregor263b47b2010-01-25 16:12:32 +00001060 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1061 return true;
1062 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1063 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001064 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1065 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001066
Douglas Gregorf5bab412010-01-22 01:00:11 +00001067 return false;
1068}
1069
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001070bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1071 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1072 return true;
1073
1074 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1075 return true;
1076
1077 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1078 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1079 return true;
1080
1081 return false;
1082}
1083
Ted Kremenek3064ef92010-08-27 21:34:58 +00001084bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1085 if (D->isDefinition()) {
1086 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1087 E = D->bases_end(); I != E; ++I) {
1088 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1089 return true;
1090 }
1091 }
1092
1093 return VisitTagDecl(D);
1094}
1095
1096
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001097bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1098 return Visit(B->getBlockDecl());
1099}
1100
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001101bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1102 // FIXME: Visit fields as well?
1103 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1104 return true;
1105
1106 return VisitExpr(E);
1107}
1108
Douglas Gregor336fd812010-01-23 00:40:08 +00001109bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1110 if (E->isArgumentType()) {
1111 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1112 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001113
Douglas Gregor336fd812010-01-23 00:40:08 +00001114 return false;
1115 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001116
Douglas Gregor336fd812010-01-23 00:40:08 +00001117 return VisitExpr(E);
1118}
1119
1120bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1121 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1122 if (Visit(TSInfo->getTypeLoc()))
1123 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001124
Douglas Gregor336fd812010-01-23 00:40:08 +00001125 return VisitCastExpr(E);
1126}
1127
1128bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1129 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1130 if (Visit(TSInfo->getTypeLoc()))
1131 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001132
Douglas Gregor336fd812010-01-23 00:40:08 +00001133 return VisitExpr(E);
1134}
1135
Douglas Gregor648220e2010-08-10 15:02:34 +00001136bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1137 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1138 Visit(E->getArgTInfo2()->getTypeLoc());
1139}
1140
1141bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1142 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1143 return true;
1144
1145 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1146}
1147
Douglas Gregorc2350e52010-03-08 16:40:19 +00001148bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001149 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1150 if (Visit(TSInfo->getTypeLoc()))
1151 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001152
1153 return VisitExpr(E);
1154}
1155
Douglas Gregor81d34662010-04-20 15:39:42 +00001156bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1157 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1158}
1159
1160
Ted Kremenek09dfa372010-02-18 05:46:33 +00001161bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001162 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1163 i != e; ++i)
1164 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001165 return true;
1166
1167 return false;
1168}
1169
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001170extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001171CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1172 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001173 // We use crash recovery to make some of our APIs more reliable, implicitly
1174 // enable it.
1175 llvm::CrashRecoveryContext::Enable();
1176
Douglas Gregora030b7c2010-01-22 20:35:53 +00001177 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001178 if (excludeDeclarationsFromPCH)
1179 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001180 if (displayDiagnostics)
1181 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001182 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001183}
1184
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001185void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001186 if (CIdx)
1187 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001188 if (getenv("LIBCLANG_TIMING"))
1189 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001190}
1191
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001192void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001193 if (CIdx) {
1194 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1195 CXXIdx->setUseExternalASTGeneration(value);
1196 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001197}
1198
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001199CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001200 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001201 if (!CIdx)
1202 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001203
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001204 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001205
Douglas Gregor28019772010-04-05 23:52:57 +00001206 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001207 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001208 CXXIdx->getOnlyLocalDecls(),
1209 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001210}
1211
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001212unsigned clang_defaultEditingTranslationUnitOptions() {
1213 return CXTranslationUnit_PrecompiledPreamble;
1214}
1215
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001216CXTranslationUnit
1217clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1218 const char *source_filename,
1219 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001220 const char **command_line_args,
1221 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001222 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001223 return clang_parseTranslationUnit(CIdx, source_filename,
1224 command_line_args, num_command_line_args,
1225 unsaved_files, num_unsaved_files,
1226 CXTranslationUnit_DetailedPreprocessingRecord);
1227}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001228
1229struct ParseTranslationUnitInfo {
1230 CXIndex CIdx;
1231 const char *source_filename;
1232 const char **command_line_args;
1233 int num_command_line_args;
1234 struct CXUnsavedFile *unsaved_files;
1235 unsigned num_unsaved_files;
1236 unsigned options;
1237 CXTranslationUnit result;
1238};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001239static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001240 ParseTranslationUnitInfo *PTUI =
1241 static_cast<ParseTranslationUnitInfo*>(UserData);
1242 CXIndex CIdx = PTUI->CIdx;
1243 const char *source_filename = PTUI->source_filename;
1244 const char **command_line_args = PTUI->command_line_args;
1245 int num_command_line_args = PTUI->num_command_line_args;
1246 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1247 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1248 unsigned options = PTUI->options;
1249 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001250
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001251 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001252 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001253
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001254 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1255
Douglas Gregor44c181a2010-07-23 00:33:23 +00001256 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001257 bool CompleteTranslationUnit
1258 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001259 bool CacheCodeCompetionResults
1260 = options & CXTranslationUnit_CacheCompletionResults;
1261
Douglas Gregor5352ac02010-01-28 00:27:43 +00001262 // Configure the diagnostics.
1263 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001264 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1265 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001266
Douglas Gregor4db64a42010-01-23 00:14:00 +00001267 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1268 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001269 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001270 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001271 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001272 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1273 Buffer));
1274 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001275
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001276 if (!CXXIdx->getUseExternalASTGeneration()) {
1277 llvm::SmallVector<const char *, 16> Args;
1278
1279 // The 'source_filename' argument is optional. If the caller does not
1280 // specify it then it is assumed that the source file is specified
1281 // in the actual argument list.
1282 if (source_filename)
1283 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001284
1285 // Since the Clang C library is primarily used by batch tools dealing with
1286 // (often very broken) source code, where spell-checking can have a
1287 // significant negative impact on performance (particularly when
1288 // precompiled headers are involved), we disable it by default.
1289 // Note that we place this argument early in the list, so that it can be
1290 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001291 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001292
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001293 Args.insert(Args.end(), command_line_args,
1294 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001295
Douglas Gregor44c181a2010-07-23 00:33:23 +00001296 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001297 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1298 Args.push_back("-Xclang");
1299 Args.push_back("-detailed-preprocessing-record");
1300 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001301
Douglas Gregor5352ac02010-01-28 00:27:43 +00001302 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001303
Ted Kremenek29b72842010-01-07 22:49:05 +00001304#ifdef USE_CRASHTRACER
1305 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001306#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001307
Daniel Dunbar94220972009-12-05 02:17:18 +00001308 llvm::OwningPtr<ASTUnit> Unit(
1309 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001310 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001311 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001312 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001313 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001314 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001315 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001316 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001317 CompleteTranslationUnit,
1318 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001319
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001320 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001321 // Make sure to check that 'Unit' is non-NULL.
1322 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001323 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1324 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001325 D != DEnd; ++D) {
1326 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001327 CXString Msg = clang_formatDiagnostic(&Diag,
1328 clang_defaultDiagnosticDisplayOptions());
1329 fprintf(stderr, "%s\n", clang_getCString(Msg));
1330 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001331 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001332#ifdef LLVM_ON_WIN32
1333 // On Windows, force a flush, since there may be multiple copies of
1334 // stderr and stdout in the file system, all with different buffers
1335 // but writing to the same device.
1336 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001337#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001338 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001339 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001340
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001341 PTUI->result = Unit.take();
1342 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001343 }
1344
Ted Kremenek139ba862009-10-22 00:03:57 +00001345 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001346 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001347
Ted Kremenek139ba862009-10-22 00:03:57 +00001348 // First add the complete path to the 'clang' executable.
1349 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001350 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001351
Ted Kremenek139ba862009-10-22 00:03:57 +00001352 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001353 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001354
Ted Kremenek139ba862009-10-22 00:03:57 +00001355 // The 'source_filename' argument is optional. If the caller does not
1356 // specify it then it is assumed that the source file is specified
1357 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001358 if (source_filename)
1359 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001360
Steve Naroff37b5ac22009-10-15 20:50:09 +00001361 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001362 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001363 char astTmpFile[L_tmpnam];
1364 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001365
1366 // Since the Clang C library is primarily used by batch tools dealing with
1367 // (often very broken) source code, where spell-checking can have a
1368 // significant negative impact on performance (particularly when
1369 // precompiled headers are involved), we disable it by default.
1370 // Note that we place this argument early in the list, so that it can be
1371 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001372 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001373
Douglas Gregor4db64a42010-01-23 00:14:00 +00001374 // Remap any unsaved files to temporary files.
1375 std::vector<llvm::sys::Path> TemporaryFiles;
1376 std::vector<std::string> RemapArgs;
1377 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001378 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001379
Douglas Gregor4db64a42010-01-23 00:14:00 +00001380 // The pointers into the elements of RemapArgs are stable because we
1381 // won't be adding anything to RemapArgs after this point.
1382 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1383 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001384
Ted Kremenek139ba862009-10-22 00:03:57 +00001385 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1386 for (int i = 0; i < num_command_line_args; ++i)
1387 if (const char *arg = command_line_args[i]) {
1388 if (strcmp(arg, "-o") == 0) {
1389 ++i; // Also skip the matching argument.
1390 continue;
1391 }
1392 if (strcmp(arg, "-emit-ast") == 0 ||
1393 strcmp(arg, "-c") == 0 ||
1394 strcmp(arg, "-fsyntax-only") == 0) {
1395 continue;
1396 }
1397
1398 // Keep the argument.
1399 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001400 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001401
Douglas Gregord93256e2010-01-28 06:00:51 +00001402 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001403 char tmpFileResults[L_tmpnam];
1404 char *tmpResultsFileName = tmpnam(tmpFileResults);
1405 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001406 TemporaryFiles.push_back(DiagnosticsFile);
1407 argv.push_back("-fdiagnostics-binary");
1408
Douglas Gregor44c181a2010-07-23 00:33:23 +00001409 // Do we need the detailed preprocessing record?
1410 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1411 argv.push_back("-Xclang");
1412 argv.push_back("-detailed-preprocessing-record");
1413 }
1414
Ted Kremenek139ba862009-10-22 00:03:57 +00001415 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001416 argv.push_back(NULL);
1417
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001418 // Invoke 'clang'.
1419 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1420 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001421 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001422 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1423 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001424 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001425 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001426 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001427
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001428 if (!ErrMsg.empty()) {
1429 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001430 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001431 I != E; ++I) {
1432 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001433 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001434 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001435 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001436
Daniel Dunbar32141c82010-02-23 20:23:45 +00001437 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001438 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001439
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001440 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001441 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001442 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001443 RemappedFiles.size(),
1444 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001445 if (ATU) {
1446 LoadSerializedDiagnostics(DiagnosticsFile,
1447 num_unsaved_files, unsaved_files,
1448 ATU->getFileManager(),
1449 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001450 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001451 } else if (CXXIdx->getDisplayDiagnostics()) {
1452 // We failed to load the ASTUnit, but we can still deserialize the
1453 // diagnostics and emit them.
1454 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001455 Diagnostic Diag;
1456 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001457 // FIXME: Faked LangOpts!
1458 LangOptions LangOpts;
1459 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1460 LoadSerializedDiagnostics(DiagnosticsFile,
1461 num_unsaved_files, unsaved_files,
1462 FileMgr, SourceMgr, Diags);
1463 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1464 DEnd = Diags.end();
1465 D != DEnd; ++D) {
1466 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001467 CXString Msg = clang_formatDiagnostic(&Diag,
1468 clang_defaultDiagnosticDisplayOptions());
1469 fprintf(stderr, "%s\n", clang_getCString(Msg));
1470 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001471 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001472
1473#ifdef LLVM_ON_WIN32
1474 // On Windows, force a flush, since there may be multiple copies of
1475 // stderr and stdout in the file system, all with different buffers
1476 // but writing to the same device.
1477 fflush(stderr);
1478#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001479 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001480
Douglas Gregor313e26c2010-02-18 23:35:40 +00001481 if (ATU) {
1482 // Make the translation unit responsible for destroying all temporary files.
1483 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1484 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001485 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001486 } else {
1487 // Destroy all of the temporary files now; they can't be referenced any
1488 // longer.
1489 llvm::sys::Path(astTmpFile).eraseFromDisk();
1490 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1491 TemporaryFiles[i].eraseFromDisk();
1492 }
1493
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001494 PTUI->result = ATU;
1495}
1496CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1497 const char *source_filename,
1498 const char **command_line_args,
1499 int num_command_line_args,
1500 struct CXUnsavedFile *unsaved_files,
1501 unsigned num_unsaved_files,
1502 unsigned options) {
1503 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1504 num_command_line_args, unsaved_files, num_unsaved_files,
1505 options, 0 };
1506 llvm::CrashRecoveryContext CRC;
1507
1508 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001509 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1510 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1511 fprintf(stderr, " 'command_line_args' : [");
1512 for (int i = 0; i != num_command_line_args; ++i) {
1513 if (i)
1514 fprintf(stderr, ", ");
1515 fprintf(stderr, "'%s'", command_line_args[i]);
1516 }
1517 fprintf(stderr, "],\n");
1518 fprintf(stderr, " 'unsaved_files' : [");
1519 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1520 if (i)
1521 fprintf(stderr, ", ");
1522 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1523 unsaved_files[i].Length);
1524 }
1525 fprintf(stderr, "],\n");
1526 fprintf(stderr, " 'options' : %d,\n", options);
1527 fprintf(stderr, "}\n");
1528
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001529 return 0;
1530 }
1531
1532 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001533}
1534
Douglas Gregor19998442010-08-13 15:35:05 +00001535unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1536 return CXSaveTranslationUnit_None;
1537}
1538
1539int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1540 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001541 if (!TU)
1542 return 1;
1543
1544 return static_cast<ASTUnit *>(TU)->Save(FileName);
1545}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001546
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001547void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001548 if (CTUnit) {
1549 // If the translation unit has been marked as unsafe to free, just discard
1550 // it.
1551 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1552 return;
1553
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001554 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001555 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001556}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001557
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001558unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1559 return CXReparse_None;
1560}
1561
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001562struct ReparseTranslationUnitInfo {
1563 CXTranslationUnit TU;
1564 unsigned num_unsaved_files;
1565 struct CXUnsavedFile *unsaved_files;
1566 unsigned options;
1567 int result;
1568};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001569static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001570 ReparseTranslationUnitInfo *RTUI =
1571 static_cast<ReparseTranslationUnitInfo*>(UserData);
1572 CXTranslationUnit TU = RTUI->TU;
1573 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1574 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1575 unsigned options = RTUI->options;
1576 (void) options;
1577 RTUI->result = 1;
1578
Douglas Gregorabc563f2010-07-19 21:46:24 +00001579 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001580 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001581
1582 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1583 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1584 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1585 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001586 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001587 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1588 Buffer));
1589 }
1590
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001591 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1592 RemappedFiles.size()))
1593 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001594}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001595int clang_reparseTranslationUnit(CXTranslationUnit TU,
1596 unsigned num_unsaved_files,
1597 struct CXUnsavedFile *unsaved_files,
1598 unsigned options) {
1599 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1600 options, 0 };
1601 llvm::CrashRecoveryContext CRC;
1602
1603 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001604 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001605 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1606 return 1;
1607 }
1608
1609 return RTUI.result;
1610}
1611
Douglas Gregordf95a132010-08-09 20:45:32 +00001612
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001613CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001614 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001615 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001616
Steve Naroff77accc12009-09-03 18:19:54 +00001617 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001618 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001619}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001620
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001621CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001622 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001623 return Result;
1624}
1625
Ted Kremenekfb480492010-01-13 21:46:36 +00001626} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001627
Ted Kremenekfb480492010-01-13 21:46:36 +00001628//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001629// CXSourceLocation and CXSourceRange Operations.
1630//===----------------------------------------------------------------------===//
1631
Douglas Gregorb9790342010-01-22 21:44:22 +00001632extern "C" {
1633CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001634 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001635 return Result;
1636}
1637
1638unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001639 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1640 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1641 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001642}
1643
1644CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1645 CXFile file,
1646 unsigned line,
1647 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001648 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001649 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001650
Douglas Gregorb9790342010-01-22 21:44:22 +00001651 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1652 SourceLocation SLoc
1653 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001654 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001655 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001656
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001657 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001658}
1659
Douglas Gregor5352ac02010-01-28 00:27:43 +00001660CXSourceRange clang_getNullRange() {
1661 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1662 return Result;
1663}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001664
Douglas Gregor5352ac02010-01-28 00:27:43 +00001665CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1666 if (begin.ptr_data[0] != end.ptr_data[0] ||
1667 begin.ptr_data[1] != end.ptr_data[1])
1668 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001669
1670 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001671 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001672 return Result;
1673}
1674
Douglas Gregor46766dc2010-01-26 19:19:08 +00001675void clang_getInstantiationLocation(CXSourceLocation location,
1676 CXFile *file,
1677 unsigned *line,
1678 unsigned *column,
1679 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001680 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1681
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001682 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001683 if (file)
1684 *file = 0;
1685 if (line)
1686 *line = 0;
1687 if (column)
1688 *column = 0;
1689 if (offset)
1690 *offset = 0;
1691 return;
1692 }
1693
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001694 const SourceManager &SM =
1695 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001696 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001697
1698 if (file)
1699 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1700 if (line)
1701 *line = SM.getInstantiationLineNumber(InstLoc);
1702 if (column)
1703 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001704 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001705 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001706}
1707
Douglas Gregor1db19de2010-01-19 21:36:55 +00001708CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001709 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001710 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001711 return Result;
1712}
1713
1714CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001715 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001716 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001717 return Result;
1718}
1719
Douglas Gregorb9790342010-01-22 21:44:22 +00001720} // end: extern "C"
1721
Douglas Gregor1db19de2010-01-19 21:36:55 +00001722//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001723// CXFile Operations.
1724//===----------------------------------------------------------------------===//
1725
1726extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001727CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001728 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001729 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001730
Steve Naroff88145032009-10-27 14:35:18 +00001731 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001732 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001733}
1734
1735time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001736 if (!SFile)
1737 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001738
Steve Naroff88145032009-10-27 14:35:18 +00001739 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1740 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001741}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001742
Douglas Gregorb9790342010-01-22 21:44:22 +00001743CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1744 if (!tu)
1745 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001746
Douglas Gregorb9790342010-01-22 21:44:22 +00001747 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001748
Douglas Gregorb9790342010-01-22 21:44:22 +00001749 FileManager &FMgr = CXXUnit->getFileManager();
1750 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1751 return const_cast<FileEntry *>(File);
1752}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001753
Ted Kremenekfb480492010-01-13 21:46:36 +00001754} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001755
Ted Kremenekfb480492010-01-13 21:46:36 +00001756//===----------------------------------------------------------------------===//
1757// CXCursor Operations.
1758//===----------------------------------------------------------------------===//
1759
Ted Kremenekfb480492010-01-13 21:46:36 +00001760static Decl *getDeclFromExpr(Stmt *E) {
1761 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1762 return RefExpr->getDecl();
1763 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1764 return ME->getMemberDecl();
1765 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1766 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001767
Ted Kremenekfb480492010-01-13 21:46:36 +00001768 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1769 return getDeclFromExpr(CE->getCallee());
1770 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1771 return getDeclFromExpr(CE->getSubExpr());
1772 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1773 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001774
Ted Kremenekfb480492010-01-13 21:46:36 +00001775 return 0;
1776}
1777
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001778static SourceLocation getLocationFromExpr(Expr *E) {
1779 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1780 return /*FIXME:*/Msg->getLeftLoc();
1781 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1782 return DRE->getLocation();
1783 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1784 return Member->getMemberLoc();
1785 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1786 return Ivar->getLocation();
1787 return E->getLocStart();
1788}
1789
Ted Kremenekfb480492010-01-13 21:46:36 +00001790extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001791
1792unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001793 CXCursorVisitor visitor,
1794 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001795 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001796
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001797 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1798 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00001799 return CursorVis.VisitChildren(parent);
1800}
1801
Douglas Gregor78205d42010-01-20 21:45:58 +00001802static CXString getDeclSpelling(Decl *D) {
1803 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1804 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001805 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001806
Douglas Gregor78205d42010-01-20 21:45:58 +00001807 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001808 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001809
Douglas Gregor78205d42010-01-20 21:45:58 +00001810 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1811 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1812 // and returns different names. NamedDecl returns the class name and
1813 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001814 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001815
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001816 llvm::SmallString<1024> S;
1817 llvm::raw_svector_ostream os(S);
1818 ND->printName(os);
1819
1820 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001821}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001822
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001823CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001824 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001825 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001826
Steve Narofff334b4e2009-09-02 18:26:48 +00001827 if (clang_isReference(C.kind)) {
1828 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001829 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001830 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001831 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001832 }
1833 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001834 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001835 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001836 }
1837 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001838 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001839 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001840 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001841 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00001842 case CXCursor_CXXBaseSpecifier: {
1843 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
1844 return createCXString(B->getType().getAsString());
1845 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001846 case CXCursor_TypeRef: {
1847 TypeDecl *Type = getCursorTypeRef(C).first;
1848 assert(Type && "Missing type decl");
1849
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001850 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1851 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001852 }
1853
Daniel Dunbaracca7252009-11-30 20:42:49 +00001854 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001855 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001856 }
1857 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001858
1859 if (clang_isExpression(C.kind)) {
1860 Decl *D = getDeclFromExpr(getCursorExpr(C));
1861 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001862 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001863 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001864 }
1865
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001866 if (C.kind == CXCursor_MacroInstantiation)
1867 return createCXString(getCursorMacroInstantiation(C)->getName()
1868 ->getNameStart());
1869
Douglas Gregor572feb22010-03-18 18:04:21 +00001870 if (C.kind == CXCursor_MacroDefinition)
1871 return createCXString(getCursorMacroDefinition(C)->getName()
1872 ->getNameStart());
1873
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001874 if (clang_isDeclaration(C.kind))
1875 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001876
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001877 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001878}
1879
Ted Kremeneke68fff62010-02-17 00:41:32 +00001880CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001881 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001882 case CXCursor_FunctionDecl:
1883 return createCXString("FunctionDecl");
1884 case CXCursor_TypedefDecl:
1885 return createCXString("TypedefDecl");
1886 case CXCursor_EnumDecl:
1887 return createCXString("EnumDecl");
1888 case CXCursor_EnumConstantDecl:
1889 return createCXString("EnumConstantDecl");
1890 case CXCursor_StructDecl:
1891 return createCXString("StructDecl");
1892 case CXCursor_UnionDecl:
1893 return createCXString("UnionDecl");
1894 case CXCursor_ClassDecl:
1895 return createCXString("ClassDecl");
1896 case CXCursor_FieldDecl:
1897 return createCXString("FieldDecl");
1898 case CXCursor_VarDecl:
1899 return createCXString("VarDecl");
1900 case CXCursor_ParmDecl:
1901 return createCXString("ParmDecl");
1902 case CXCursor_ObjCInterfaceDecl:
1903 return createCXString("ObjCInterfaceDecl");
1904 case CXCursor_ObjCCategoryDecl:
1905 return createCXString("ObjCCategoryDecl");
1906 case CXCursor_ObjCProtocolDecl:
1907 return createCXString("ObjCProtocolDecl");
1908 case CXCursor_ObjCPropertyDecl:
1909 return createCXString("ObjCPropertyDecl");
1910 case CXCursor_ObjCIvarDecl:
1911 return createCXString("ObjCIvarDecl");
1912 case CXCursor_ObjCInstanceMethodDecl:
1913 return createCXString("ObjCInstanceMethodDecl");
1914 case CXCursor_ObjCClassMethodDecl:
1915 return createCXString("ObjCClassMethodDecl");
1916 case CXCursor_ObjCImplementationDecl:
1917 return createCXString("ObjCImplementationDecl");
1918 case CXCursor_ObjCCategoryImplDecl:
1919 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001920 case CXCursor_CXXMethod:
1921 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001922 case CXCursor_UnexposedDecl:
1923 return createCXString("UnexposedDecl");
1924 case CXCursor_ObjCSuperClassRef:
1925 return createCXString("ObjCSuperClassRef");
1926 case CXCursor_ObjCProtocolRef:
1927 return createCXString("ObjCProtocolRef");
1928 case CXCursor_ObjCClassRef:
1929 return createCXString("ObjCClassRef");
1930 case CXCursor_TypeRef:
1931 return createCXString("TypeRef");
1932 case CXCursor_UnexposedExpr:
1933 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001934 case CXCursor_BlockExpr:
1935 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001936 case CXCursor_DeclRefExpr:
1937 return createCXString("DeclRefExpr");
1938 case CXCursor_MemberRefExpr:
1939 return createCXString("MemberRefExpr");
1940 case CXCursor_CallExpr:
1941 return createCXString("CallExpr");
1942 case CXCursor_ObjCMessageExpr:
1943 return createCXString("ObjCMessageExpr");
1944 case CXCursor_UnexposedStmt:
1945 return createCXString("UnexposedStmt");
1946 case CXCursor_InvalidFile:
1947 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001948 case CXCursor_InvalidCode:
1949 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001950 case CXCursor_NoDeclFound:
1951 return createCXString("NoDeclFound");
1952 case CXCursor_NotImplemented:
1953 return createCXString("NotImplemented");
1954 case CXCursor_TranslationUnit:
1955 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001956 case CXCursor_UnexposedAttr:
1957 return createCXString("UnexposedAttr");
1958 case CXCursor_IBActionAttr:
1959 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001960 case CXCursor_IBOutletAttr:
1961 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00001962 case CXCursor_IBOutletCollectionAttr:
1963 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001964 case CXCursor_PreprocessingDirective:
1965 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001966 case CXCursor_MacroDefinition:
1967 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001968 case CXCursor_MacroInstantiation:
1969 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001970 case CXCursor_Namespace:
1971 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00001972 case CXCursor_LinkageSpec:
1973 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00001974 case CXCursor_CXXBaseSpecifier:
1975 return createCXString("C++ base class specifier");
Steve Naroff89922f82009-08-31 00:59:03 +00001976 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001977
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001978 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001979 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001980}
Steve Naroff89922f82009-08-31 00:59:03 +00001981
Ted Kremeneke68fff62010-02-17 00:41:32 +00001982enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1983 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001984 CXClientData client_data) {
1985 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1986 *BestCursor = cursor;
1987 return CXChildVisit_Recurse;
1988}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001989
Douglas Gregorb9790342010-01-22 21:44:22 +00001990CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1991 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001992 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001993
Douglas Gregorb9790342010-01-22 21:44:22 +00001994 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00001995 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1996
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00001997 // Translate the given source location to make it point at the beginning of
1998 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00001999 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002000
2001 // Guard against an invalid SourceLocation, or we may assert in one
2002 // of the following calls.
2003 if (SLoc.isInvalid())
2004 return clang_getNullCursor();
2005
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002006 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2007 CXXUnit->getASTContext().getLangOptions());
2008
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002009 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2010 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002011 // FIXME: Would be great to have a "hint" cursor, then walk from that
2012 // hint cursor upward until we find a cursor whose source range encloses
2013 // the region of interest, rather than starting from the translation unit.
2014 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002015 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002016 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002017 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002018 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002019 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002020}
2021
Ted Kremenek73885552009-11-17 19:28:59 +00002022CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002023 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002024}
2025
2026unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002027 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002028}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002029
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002030unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002031 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2032}
2033
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002034unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002035 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2036}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002037
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002038unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002039 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2040}
2041
Douglas Gregor97b98722010-01-19 23:20:36 +00002042unsigned clang_isExpression(enum CXCursorKind K) {
2043 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2044}
2045
2046unsigned clang_isStatement(enum CXCursorKind K) {
2047 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2048}
2049
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002050unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2051 return K == CXCursor_TranslationUnit;
2052}
2053
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002054unsigned clang_isPreprocessing(enum CXCursorKind K) {
2055 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2056}
2057
Ted Kremenekad6eff62010-03-08 21:17:29 +00002058unsigned clang_isUnexposed(enum CXCursorKind K) {
2059 switch (K) {
2060 case CXCursor_UnexposedDecl:
2061 case CXCursor_UnexposedExpr:
2062 case CXCursor_UnexposedStmt:
2063 case CXCursor_UnexposedAttr:
2064 return true;
2065 default:
2066 return false;
2067 }
2068}
2069
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002070CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002071 return C.kind;
2072}
2073
Douglas Gregor98258af2010-01-18 22:46:11 +00002074CXSourceLocation clang_getCursorLocation(CXCursor C) {
2075 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002076 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002077 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002078 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2079 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002080 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002081 }
2082
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002083 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002084 std::pair<ObjCProtocolDecl *, SourceLocation> P
2085 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002086 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002087 }
2088
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002089 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002090 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2091 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002092 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002093 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002094
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002095 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002096 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002097 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002098 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002099
2100 case CXCursor_CXXBaseSpecifier: {
2101 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2102 return clang_getNullLocation();
2103 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002104
Douglas Gregorf46034a2010-01-18 23:41:10 +00002105 default:
2106 // FIXME: Need a way to enumerate all non-reference cases.
2107 llvm_unreachable("Missed a reference kind");
2108 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002109 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002110
2111 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002112 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002113 getLocationFromExpr(getCursorExpr(C)));
2114
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002115 if (C.kind == CXCursor_PreprocessingDirective) {
2116 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2117 return cxloc::translateSourceLocation(getCursorContext(C), L);
2118 }
Douglas Gregor48072312010-03-18 15:23:44 +00002119
2120 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002121 SourceLocation L
2122 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002123 return cxloc::translateSourceLocation(getCursorContext(C), L);
2124 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002125
2126 if (C.kind == CXCursor_MacroDefinition) {
2127 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2128 return cxloc::translateSourceLocation(getCursorContext(C), L);
2129 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002130
Ted Kremenek9a700d22010-05-12 06:16:13 +00002131 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002132 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002133
Douglas Gregorf46034a2010-01-18 23:41:10 +00002134 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002135 SourceLocation Loc = D->getLocation();
2136 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2137 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002138 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002139}
Douglas Gregora7bde202010-01-19 00:34:46 +00002140
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002141} // end extern "C"
2142
2143static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002144 if (clang_isReference(C.kind)) {
2145 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002146 case CXCursor_ObjCSuperClassRef:
2147 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002148
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002149 case CXCursor_ObjCProtocolRef:
2150 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002151
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002152 case CXCursor_ObjCClassRef:
2153 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002154
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002155 case CXCursor_TypeRef:
2156 return getCursorTypeRef(C).second;
Ted Kremenek3064ef92010-08-27 21:34:58 +00002157
2158 case CXCursor_CXXBaseSpecifier:
2159 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2160 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002161
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002162 default:
2163 // FIXME: Need a way to enumerate all non-reference cases.
2164 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002165 }
2166 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002167
2168 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002169 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002170
2171 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002172 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002173
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002174 if (C.kind == CXCursor_PreprocessingDirective)
2175 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002176
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002177 if (C.kind == CXCursor_MacroInstantiation)
2178 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002179
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002180 if (C.kind == CXCursor_MacroDefinition)
2181 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002182
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002183 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2184 return getCursorDecl(C)->getSourceRange();
2185
2186 return SourceRange();
2187}
2188
2189extern "C" {
2190
2191CXSourceRange clang_getCursorExtent(CXCursor C) {
2192 SourceRange R = getRawCursorExtent(C);
2193 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002194 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002195
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002196 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002197}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002198
2199CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002200 if (clang_isInvalid(C.kind))
2201 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002202
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002203 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002204 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002205 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002206
Douglas Gregor97b98722010-01-19 23:20:36 +00002207 if (clang_isExpression(C.kind)) {
2208 Decl *D = getDeclFromExpr(getCursorExpr(C));
2209 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002210 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002211 return clang_getNullCursor();
2212 }
2213
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002214 if (C.kind == CXCursor_MacroInstantiation) {
2215 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2216 return MakeMacroDefinitionCursor(Def, CXXUnit);
2217 }
2218
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002219 if (!clang_isReference(C.kind))
2220 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002221
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002222 switch (C.kind) {
2223 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002224 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002225
2226 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002227 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002228
2229 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002230 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002231
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002232 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002233 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenek3064ef92010-08-27 21:34:58 +00002234
2235 case CXCursor_CXXBaseSpecifier: {
2236 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2237 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2238 CXXUnit));
2239 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002240
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002241 default:
2242 // We would prefer to enumerate all non-reference cursor kinds here.
2243 llvm_unreachable("Unhandled reference cursor kind");
2244 break;
2245 }
2246 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002247
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002248 return clang_getNullCursor();
2249}
2250
Douglas Gregorb6998662010-01-19 19:34:47 +00002251CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002252 if (clang_isInvalid(C.kind))
2253 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002254
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002255 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002256
Douglas Gregorb6998662010-01-19 19:34:47 +00002257 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002258 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002259 C = clang_getCursorReferenced(C);
2260 WasReference = true;
2261 }
2262
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002263 if (C.kind == CXCursor_MacroInstantiation)
2264 return clang_getCursorReferenced(C);
2265
Douglas Gregorb6998662010-01-19 19:34:47 +00002266 if (!clang_isDeclaration(C.kind))
2267 return clang_getNullCursor();
2268
2269 Decl *D = getCursorDecl(C);
2270 if (!D)
2271 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002272
Douglas Gregorb6998662010-01-19 19:34:47 +00002273 switch (D->getKind()) {
2274 // Declaration kinds that don't really separate the notions of
2275 // declaration and definition.
2276 case Decl::Namespace:
2277 case Decl::Typedef:
2278 case Decl::TemplateTypeParm:
2279 case Decl::EnumConstant:
2280 case Decl::Field:
2281 case Decl::ObjCIvar:
2282 case Decl::ObjCAtDefsField:
2283 case Decl::ImplicitParam:
2284 case Decl::ParmVar:
2285 case Decl::NonTypeTemplateParm:
2286 case Decl::TemplateTemplateParm:
2287 case Decl::ObjCCategoryImpl:
2288 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002289 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002290 case Decl::LinkageSpec:
2291 case Decl::ObjCPropertyImpl:
2292 case Decl::FileScopeAsm:
2293 case Decl::StaticAssert:
2294 case Decl::Block:
2295 return C;
2296
2297 // Declaration kinds that don't make any sense here, but are
2298 // nonetheless harmless.
2299 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002300 break;
2301
2302 // Declaration kinds for which the definition is not resolvable.
2303 case Decl::UnresolvedUsingTypename:
2304 case Decl::UnresolvedUsingValue:
2305 break;
2306
2307 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002308 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2309 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002310
2311 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002312 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002313
2314 case Decl::Enum:
2315 case Decl::Record:
2316 case Decl::CXXRecord:
2317 case Decl::ClassTemplateSpecialization:
2318 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002319 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002320 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002321 return clang_getNullCursor();
2322
2323 case Decl::Function:
2324 case Decl::CXXMethod:
2325 case Decl::CXXConstructor:
2326 case Decl::CXXDestructor:
2327 case Decl::CXXConversion: {
2328 const FunctionDecl *Def = 0;
2329 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002330 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002331 return clang_getNullCursor();
2332 }
2333
2334 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002335 // Ask the variable if it has a definition.
2336 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2337 return MakeCXCursor(Def, CXXUnit);
2338 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002339 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002340
Douglas Gregorb6998662010-01-19 19:34:47 +00002341 case Decl::FunctionTemplate: {
2342 const FunctionDecl *Def = 0;
2343 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002344 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002345 return clang_getNullCursor();
2346 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002347
Douglas Gregorb6998662010-01-19 19:34:47 +00002348 case Decl::ClassTemplate: {
2349 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002350 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002351 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002352 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002353 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002354 return clang_getNullCursor();
2355 }
2356
2357 case Decl::Using: {
2358 UsingDecl *Using = cast<UsingDecl>(D);
2359 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002360 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2361 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002362 S != SEnd; ++S) {
2363 if (Def != clang_getNullCursor()) {
2364 // FIXME: We have no way to return multiple results.
2365 return clang_getNullCursor();
2366 }
2367
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002368 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002369 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002370 }
2371
2372 return Def;
2373 }
2374
2375 case Decl::UsingShadow:
2376 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002377 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002378 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002379
2380 case Decl::ObjCMethod: {
2381 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2382 if (Method->isThisDeclarationADefinition())
2383 return C;
2384
2385 // Dig out the method definition in the associated
2386 // @implementation, if we have it.
2387 // FIXME: The ASTs should make finding the definition easier.
2388 if (ObjCInterfaceDecl *Class
2389 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2390 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2391 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2392 Method->isInstanceMethod()))
2393 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002394 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002395
2396 return clang_getNullCursor();
2397 }
2398
2399 case Decl::ObjCCategory:
2400 if (ObjCCategoryImplDecl *Impl
2401 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002402 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002403 return clang_getNullCursor();
2404
2405 case Decl::ObjCProtocol:
2406 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2407 return C;
2408 return clang_getNullCursor();
2409
2410 case Decl::ObjCInterface:
2411 // There are two notions of a "definition" for an Objective-C
2412 // class: the interface and its implementation. When we resolved a
2413 // reference to an Objective-C class, produce the @interface as
2414 // the definition; when we were provided with the interface,
2415 // produce the @implementation as the definition.
2416 if (WasReference) {
2417 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2418 return C;
2419 } else if (ObjCImplementationDecl *Impl
2420 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002421 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002422 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002423
Douglas Gregorb6998662010-01-19 19:34:47 +00002424 case Decl::ObjCProperty:
2425 // FIXME: We don't really know where to find the
2426 // ObjCPropertyImplDecls that implement this property.
2427 return clang_getNullCursor();
2428
2429 case Decl::ObjCCompatibleAlias:
2430 if (ObjCInterfaceDecl *Class
2431 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2432 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002433 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002434
Douglas Gregorb6998662010-01-19 19:34:47 +00002435 return clang_getNullCursor();
2436
2437 case Decl::ObjCForwardProtocol: {
2438 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2439 if (Forward->protocol_size() == 1)
2440 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002441 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002442 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002443
2444 // FIXME: Cannot return multiple definitions.
2445 return clang_getNullCursor();
2446 }
2447
2448 case Decl::ObjCClass: {
2449 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2450 if (Class->size() == 1) {
2451 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2452 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002453 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002454 return clang_getNullCursor();
2455 }
2456
2457 // FIXME: Cannot return multiple definitions.
2458 return clang_getNullCursor();
2459 }
2460
2461 case Decl::Friend:
2462 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002463 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002464 return clang_getNullCursor();
2465
2466 case Decl::FriendTemplate:
2467 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002468 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002469 return clang_getNullCursor();
2470 }
2471
2472 return clang_getNullCursor();
2473}
2474
2475unsigned clang_isCursorDefinition(CXCursor C) {
2476 if (!clang_isDeclaration(C.kind))
2477 return 0;
2478
2479 return clang_getCursorDefinition(C) == C;
2480}
2481
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002482void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002483 const char **startBuf,
2484 const char **endBuf,
2485 unsigned *startLine,
2486 unsigned *startColumn,
2487 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002488 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002489 assert(getCursorDecl(C) && "CXCursor has null decl");
2490 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002491 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2492 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002493
Steve Naroff4ade6d62009-09-23 17:52:52 +00002494 SourceManager &SM = FD->getASTContext().getSourceManager();
2495 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2496 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2497 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2498 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2499 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2500 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2501}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002502
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002503void clang_enableStackTraces(void) {
2504 llvm::sys::PrintStackTraceOnErrorSignal();
2505}
2506
Ted Kremenekfb480492010-01-13 21:46:36 +00002507} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002508
Ted Kremenekfb480492010-01-13 21:46:36 +00002509//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002510// Token-based Operations.
2511//===----------------------------------------------------------------------===//
2512
2513/* CXToken layout:
2514 * int_data[0]: a CXTokenKind
2515 * int_data[1]: starting token location
2516 * int_data[2]: token length
2517 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002518 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002519 * otherwise unused.
2520 */
2521extern "C" {
2522
2523CXTokenKind clang_getTokenKind(CXToken CXTok) {
2524 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2525}
2526
2527CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2528 switch (clang_getTokenKind(CXTok)) {
2529 case CXToken_Identifier:
2530 case CXToken_Keyword:
2531 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002532 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2533 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002534
2535 case CXToken_Literal: {
2536 // We have stashed the starting pointer in the ptr_data field. Use it.
2537 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002538 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002539 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002540
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002541 case CXToken_Punctuation:
2542 case CXToken_Comment:
2543 break;
2544 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002545
2546 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002547 // deconstructing the source location.
2548 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2549 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002550 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002551
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002552 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2553 std::pair<FileID, unsigned> LocInfo
2554 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002555 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002556 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002557 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2558 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002559 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002560
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002561 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002562}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002563
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002564CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2565 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2566 if (!CXXUnit)
2567 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002568
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002569 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2570 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2571}
2572
2573CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2574 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002575 if (!CXXUnit)
2576 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002577
2578 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002579 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2580}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002581
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002582void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2583 CXToken **Tokens, unsigned *NumTokens) {
2584 if (Tokens)
2585 *Tokens = 0;
2586 if (NumTokens)
2587 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002588
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002589 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2590 if (!CXXUnit || !Tokens || !NumTokens)
2591 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002592
Douglas Gregorbdf60622010-03-05 21:16:25 +00002593 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2594
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002595 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002596 if (R.isInvalid())
2597 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002598
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002599 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2600 std::pair<FileID, unsigned> BeginLocInfo
2601 = SourceMgr.getDecomposedLoc(R.getBegin());
2602 std::pair<FileID, unsigned> EndLocInfo
2603 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002604
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002605 // Cannot tokenize across files.
2606 if (BeginLocInfo.first != EndLocInfo.first)
2607 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002608
2609 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002610 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002611 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002612 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002613 if (Invalid)
2614 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002615
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002616 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2617 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002618 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002619 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002620
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002621 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002622 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002623 llvm::SmallVector<CXToken, 32> CXTokens;
2624 Token Tok;
2625 do {
2626 // Lex the next token
2627 Lex.LexFromRawLexer(Tok);
2628 if (Tok.is(tok::eof))
2629 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002630
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002631 // Initialize the CXToken.
2632 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002633
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002634 // - Common fields
2635 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2636 CXTok.int_data[2] = Tok.getLength();
2637 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002638
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002639 // - Kind-specific fields
2640 if (Tok.isLiteral()) {
2641 CXTok.int_data[0] = CXToken_Literal;
2642 CXTok.ptr_data = (void *)Tok.getLiteralData();
2643 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002644 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002645 std::pair<FileID, unsigned> LocInfo
2646 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002647 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002648 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002649 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2650 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002651 return;
2652
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002653 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002654 IdentifierInfo *II
2655 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002656
2657 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2658 CXTok.int_data[0] = CXToken_Keyword;
2659 }
2660 else {
2661 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2662 CXToken_Identifier
2663 : CXToken_Keyword;
2664 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002665 CXTok.ptr_data = II;
2666 } else if (Tok.is(tok::comment)) {
2667 CXTok.int_data[0] = CXToken_Comment;
2668 CXTok.ptr_data = 0;
2669 } else {
2670 CXTok.int_data[0] = CXToken_Punctuation;
2671 CXTok.ptr_data = 0;
2672 }
2673 CXTokens.push_back(CXTok);
2674 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002675
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002676 if (CXTokens.empty())
2677 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002678
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002679 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2680 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2681 *NumTokens = CXTokens.size();
2682}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002683
Ted Kremenek6db61092010-05-05 00:55:15 +00002684void clang_disposeTokens(CXTranslationUnit TU,
2685 CXToken *Tokens, unsigned NumTokens) {
2686 free(Tokens);
2687}
2688
2689} // end: extern "C"
2690
2691//===----------------------------------------------------------------------===//
2692// Token annotation APIs.
2693//===----------------------------------------------------------------------===//
2694
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002695typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002696static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2697 CXCursor parent,
2698 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002699namespace {
2700class AnnotateTokensWorker {
2701 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002702 CXToken *Tokens;
2703 CXCursor *Cursors;
2704 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002705 unsigned TokIdx;
2706 CursorVisitor AnnotateVis;
2707 SourceManager &SrcMgr;
2708
2709 bool MoreTokens() const { return TokIdx < NumTokens; }
2710 unsigned NextToken() const { return TokIdx; }
2711 void AdvanceToken() { ++TokIdx; }
2712 SourceLocation GetTokenLoc(unsigned tokI) {
2713 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2714 }
2715
Ted Kremenek6db61092010-05-05 00:55:15 +00002716public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002717 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002718 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2719 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002720 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002721 NumTokens(numTokens), TokIdx(0),
2722 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2723 Decl::MaxPCHLevel, RegionOfInterest),
2724 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002725
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002726 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002727 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002728 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002729};
2730}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002731
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002732void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2733 // Walk the AST within the region of interest, annotating tokens
2734 // along the way.
2735 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002736
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002737 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2738 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2739 if (Pos != Annotated.end())
2740 Cursors[I] = Pos->second;
2741 }
2742
2743 // Finish up annotating any tokens left.
2744 if (!MoreTokens())
2745 return;
2746
2747 const CXCursor &C = clang_getNullCursor();
2748 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2749 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2750 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002751 }
2752}
2753
Ted Kremenek6db61092010-05-05 00:55:15 +00002754enum CXChildVisitResult
2755AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002756 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2757 // We can always annotate a preprocessing directive/macro instantiation.
2758 if (clang_isPreprocessing(cursor.kind)) {
2759 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002760 return CXChildVisit_Recurse;
2761 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002762
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002763 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00002764
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002765 if (cursorRange.isInvalid())
2766 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002767
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002768 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2769
Ted Kremeneka333c662010-05-12 05:29:33 +00002770 // Adjust the annotated range based specific declarations.
2771 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2772 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002773 Decl *D = cxcursor::getCursorDecl(cursor);
2774 // Don't visit synthesized ObjC methods, since they have no syntatic
2775 // representation in the source.
2776 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2777 if (MD->isSynthesized())
2778 return CXChildVisit_Continue;
2779 }
2780 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002781 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2782 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002783 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002784 if (TLoc.isValid() &&
2785 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002786 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002787 }
2788 }
2789 }
2790
Ted Kremenek3f404602010-08-14 01:14:06 +00002791 // If the location of the cursor occurs within a macro instantiation, record
2792 // the spelling location of the cursor in our annotation map. We can then
2793 // paper over the token labelings during a post-processing step to try and
2794 // get cursor mappings for tokens that are the *arguments* of a macro
2795 // instantiation.
2796 if (L.isMacroID()) {
2797 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
2798 // Only invalidate the old annotation if it isn't part of a preprocessing
2799 // directive. Here we assume that the default construction of CXCursor
2800 // results in CXCursor.kind being an initialized value (i.e., 0). If
2801 // this isn't the case, we can fix by doing lookup + insertion.
2802
2803 CXCursor &oldC = Annotated[rawEncoding];
2804 if (!clang_isPreprocessing(oldC.kind))
2805 oldC = cursor;
2806 }
2807
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002808 const enum CXCursorKind K = clang_getCursorKind(parent);
2809 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00002810 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
2811 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002812
2813 while (MoreTokens()) {
2814 const unsigned I = NextToken();
2815 SourceLocation TokLoc = GetTokenLoc(I);
2816 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2817 case RangeBefore:
2818 Cursors[I] = updateC;
2819 AdvanceToken();
2820 continue;
2821 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002822 case RangeOverlap:
2823 break;
2824 }
2825 break;
2826 }
2827
2828 // Visit children to get their cursor information.
2829 const unsigned BeforeChildren = NextToken();
2830 VisitChildren(cursor);
2831 const unsigned AfterChildren = NextToken();
2832
2833 // Adjust 'Last' to the last token within the extent of the cursor.
2834 while (MoreTokens()) {
2835 const unsigned I = NextToken();
2836 SourceLocation TokLoc = GetTokenLoc(I);
2837 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2838 case RangeBefore:
2839 assert(0 && "Infeasible");
2840 case RangeAfter:
2841 break;
2842 case RangeOverlap:
2843 Cursors[I] = updateC;
2844 AdvanceToken();
2845 continue;
2846 }
2847 break;
2848 }
2849 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002850
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002851 // Scan the tokens that are at the beginning of the cursor, but are not
2852 // capture by the child cursors.
2853
2854 // For AST elements within macros, rely on a post-annotate pass to
2855 // to correctly annotate the tokens with cursors. Otherwise we can
2856 // get confusing results of having tokens that map to cursors that really
2857 // are expanded by an instantiation.
2858 if (L.isMacroID())
2859 cursor = clang_getNullCursor();
2860
2861 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2862 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2863 break;
2864 Cursors[I] = cursor;
2865 }
2866 // Scan the tokens that are at the end of the cursor, but are not captured
2867 // but the child cursors.
2868 for (unsigned I = AfterChildren; I != Last; ++I)
2869 Cursors[I] = cursor;
2870
2871 TokIdx = Last;
2872 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002873}
2874
Ted Kremenek6db61092010-05-05 00:55:15 +00002875static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2876 CXCursor parent,
2877 CXClientData client_data) {
2878 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2879}
2880
2881extern "C" {
2882
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002883void clang_annotateTokens(CXTranslationUnit TU,
2884 CXToken *Tokens, unsigned NumTokens,
2885 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002886
2887 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002888 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002889
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002890 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002891 if (!CXXUnit) {
2892 // Any token we don't specifically annotate will have a NULL cursor.
2893 const CXCursor &C = clang_getNullCursor();
2894 for (unsigned I = 0; I != NumTokens; ++I)
2895 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002896 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002897 }
2898
Douglas Gregorbdf60622010-03-05 21:16:25 +00002899 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002900
Douglas Gregor0396f462010-03-19 05:22:59 +00002901 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002902 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002903 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2904 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002905 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
2906 clang_getTokenLocation(TU,
2907 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002908
Douglas Gregor0396f462010-03-19 05:22:59 +00002909 // A mapping from the source locations found when re-lexing or traversing the
2910 // region of interest to the corresponding cursors.
2911 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002912
2913 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002914 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002915 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2916 std::pair<FileID, unsigned> BeginLocInfo
2917 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2918 std::pair<FileID, unsigned> EndLocInfo
2919 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002920
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002921 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002922 bool Invalid = false;
2923 if (BeginLocInfo.first == EndLocInfo.first &&
2924 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2925 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002926 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2927 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002928 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002929 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002930 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002931
2932 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002933 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002934 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002935 Token Tok;
2936 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002937
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002938 reprocess:
2939 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2940 // We have found a preprocessing directive. Gobble it up so that we
2941 // don't see it while preprocessing these tokens later, but keep track of
2942 // all of the token locations inside this preprocessing directive so that
2943 // we can annotate them appropriately.
2944 //
2945 // FIXME: Some simple tests here could identify macro definitions and
2946 // #undefs, to provide specific cursor kinds for those.
2947 std::vector<SourceLocation> Locations;
2948 do {
2949 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002950 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002951 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002952
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002953 using namespace cxcursor;
2954 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002955 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2956 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00002957 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002958 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2959 Annotated[Locations[I].getRawEncoding()] = Cursor;
2960 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002961
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002962 if (Tok.isAtStartOfLine())
2963 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002964
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002965 continue;
2966 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002967
Douglas Gregor48072312010-03-18 15:23:44 +00002968 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002969 break;
2970 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002971 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002972
Douglas Gregor0396f462010-03-19 05:22:59 +00002973 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002974 // a specific cursor.
2975 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2976 CXXUnit, RegionOfInterest);
2977 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002978}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002979} // end: extern "C"
2980
2981//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002982// Operations for querying linkage of a cursor.
2983//===----------------------------------------------------------------------===//
2984
2985extern "C" {
2986CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002987 if (!clang_isDeclaration(cursor.kind))
2988 return CXLinkage_Invalid;
2989
Ted Kremenek16b42592010-03-03 06:36:57 +00002990 Decl *D = cxcursor::getCursorDecl(cursor);
2991 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2992 switch (ND->getLinkage()) {
2993 case NoLinkage: return CXLinkage_NoLinkage;
2994 case InternalLinkage: return CXLinkage_Internal;
2995 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2996 case ExternalLinkage: return CXLinkage_External;
2997 };
2998
2999 return CXLinkage_Invalid;
3000}
3001} // end: extern "C"
3002
3003//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003004// Operations for querying language of a cursor.
3005//===----------------------------------------------------------------------===//
3006
3007static CXLanguageKind getDeclLanguage(const Decl *D) {
3008 switch (D->getKind()) {
3009 default:
3010 break;
3011 case Decl::ImplicitParam:
3012 case Decl::ObjCAtDefsField:
3013 case Decl::ObjCCategory:
3014 case Decl::ObjCCategoryImpl:
3015 case Decl::ObjCClass:
3016 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003017 case Decl::ObjCForwardProtocol:
3018 case Decl::ObjCImplementation:
3019 case Decl::ObjCInterface:
3020 case Decl::ObjCIvar:
3021 case Decl::ObjCMethod:
3022 case Decl::ObjCProperty:
3023 case Decl::ObjCPropertyImpl:
3024 case Decl::ObjCProtocol:
3025 return CXLanguage_ObjC;
3026 case Decl::CXXConstructor:
3027 case Decl::CXXConversion:
3028 case Decl::CXXDestructor:
3029 case Decl::CXXMethod:
3030 case Decl::CXXRecord:
3031 case Decl::ClassTemplate:
3032 case Decl::ClassTemplatePartialSpecialization:
3033 case Decl::ClassTemplateSpecialization:
3034 case Decl::Friend:
3035 case Decl::FriendTemplate:
3036 case Decl::FunctionTemplate:
3037 case Decl::LinkageSpec:
3038 case Decl::Namespace:
3039 case Decl::NamespaceAlias:
3040 case Decl::NonTypeTemplateParm:
3041 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003042 case Decl::TemplateTemplateParm:
3043 case Decl::TemplateTypeParm:
3044 case Decl::UnresolvedUsingTypename:
3045 case Decl::UnresolvedUsingValue:
3046 case Decl::Using:
3047 case Decl::UsingDirective:
3048 case Decl::UsingShadow:
3049 return CXLanguage_CPlusPlus;
3050 }
3051
3052 return CXLanguage_C;
3053}
3054
3055extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003056
3057enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3058 if (clang_isDeclaration(cursor.kind))
3059 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3060 if (D->hasAttr<UnavailableAttr>() ||
3061 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3062 return CXAvailability_Available;
3063
3064 if (D->hasAttr<DeprecatedAttr>())
3065 return CXAvailability_Deprecated;
3066 }
3067
3068 return CXAvailability_Available;
3069}
3070
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003071CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3072 if (clang_isDeclaration(cursor.kind))
3073 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3074
3075 return CXLanguage_Invalid;
3076}
3077} // end: extern "C"
3078
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003079
3080//===----------------------------------------------------------------------===//
3081// C++ AST instrospection.
3082//===----------------------------------------------------------------------===//
3083
3084extern "C" {
3085unsigned clang_CXXMethod_isStatic(CXCursor C) {
3086 if (!clang_isDeclaration(C.kind))
3087 return 0;
3088 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
3089 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003090}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003091
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003092} // end: extern "C"
3093
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003094//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003095// Attribute introspection.
3096//===----------------------------------------------------------------------===//
3097
3098extern "C" {
3099CXType clang_getIBOutletCollectionType(CXCursor C) {
3100 if (C.kind != CXCursor_IBOutletCollectionAttr)
3101 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3102
3103 IBOutletCollectionAttr *A =
3104 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3105
3106 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3107}
3108} // end: extern "C"
3109
3110//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003111// CXString Operations.
3112//===----------------------------------------------------------------------===//
3113
3114extern "C" {
3115const char *clang_getCString(CXString string) {
3116 return string.Spelling;
3117}
3118
3119void clang_disposeString(CXString string) {
3120 if (string.MustFreeString && string.Spelling)
3121 free((void*)string.Spelling);
3122}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003123
Ted Kremenekfb480492010-01-13 21:46:36 +00003124} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003125
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003126namespace clang { namespace cxstring {
3127CXString createCXString(const char *String, bool DupString){
3128 CXString Str;
3129 if (DupString) {
3130 Str.Spelling = strdup(String);
3131 Str.MustFreeString = 1;
3132 } else {
3133 Str.Spelling = String;
3134 Str.MustFreeString = 0;
3135 }
3136 return Str;
3137}
3138
3139CXString createCXString(llvm::StringRef String, bool DupString) {
3140 CXString Result;
3141 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3142 char *Spelling = (char *)malloc(String.size() + 1);
3143 memmove(Spelling, String.data(), String.size());
3144 Spelling[String.size()] = 0;
3145 Result.Spelling = Spelling;
3146 Result.MustFreeString = 1;
3147 } else {
3148 Result.Spelling = String.data();
3149 Result.MustFreeString = 0;
3150 }
3151 return Result;
3152}
3153}}
3154
Ted Kremenek04bb7162010-01-22 22:44:15 +00003155//===----------------------------------------------------------------------===//
3156// Misc. utility functions.
3157//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003158
Ted Kremenek04bb7162010-01-22 22:44:15 +00003159extern "C" {
3160
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003161CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003162 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003163}
3164
3165} // end: extern "C"