blob: fc665926f2895582c62ce8ac4e5ead5f7e98915c [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
Douglas Gregor01829d32010-08-31 14:41:23 +0000315 // Name visitor
316 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
317
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000318 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000319 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000320 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000321 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000322 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
323 bool VisitTagTypeLoc(TagTypeLoc TL);
324 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
325 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000326 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000327 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
328 bool VisitPointerTypeLoc(PointerTypeLoc TL);
329 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
330 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
331 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
332 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000333 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000334 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000335 // FIXME: Implement for TemplateSpecializationTypeLoc
336 // FIXME: Implement visitors here when the unimplemented TypeLocs get
337 // implemented
338 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
339 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000340
Douglas Gregora59e3902010-01-21 23:27:09 +0000341 // Statement visitors
342 bool VisitStmt(Stmt *S);
343 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000344 // FIXME: LabelStmt label?
345 bool VisitIfStmt(IfStmt *S);
346 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000347 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000348 bool VisitWhileStmt(WhileStmt *S);
349 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000350// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000351
Douglas Gregor336fd812010-01-23 00:40:08 +0000352 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000353 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
354 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000355 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000356 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000357 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000358 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000359 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000360 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000361 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000362 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000363 // FIXME: AddrLabelExpr (once we have cursors for labels)
364 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
365 bool VisitVAArgExpr(VAArgExpr *E);
366 // FIXME: InitListExpr (for the designators)
367 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000368};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000369
Ted Kremenekab188932010-01-05 19:32:54 +0000370} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000371
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000372static SourceRange getRawCursorExtent(CXCursor C);
373
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000374RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000375 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
376}
377
Douglas Gregorb1373d02010-01-20 20:59:29 +0000378/// \brief Visit the given cursor and, if requested by the visitor,
379/// its children.
380///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000381/// \param Cursor the cursor to visit.
382///
383/// \param CheckRegionOfInterest if true, then the caller already checked that
384/// this cursor is within the region of interest.
385///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000386/// \returns true if the visitation should be aborted, false if it
387/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000388bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000389 if (clang_isInvalid(Cursor.kind))
390 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000391
Douglas Gregorb1373d02010-01-20 20:59:29 +0000392 if (clang_isDeclaration(Cursor.kind)) {
393 Decl *D = getCursorDecl(Cursor);
394 assert(D && "Invalid declaration cursor");
395 if (D->getPCHLevel() > MaxPCHLevel)
396 return false;
397
398 if (D->isImplicit())
399 return false;
400 }
401
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000402 // If we have a range of interest, and this cursor doesn't intersect with it,
403 // we're done.
404 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000405 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000406 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000407 return false;
408 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000409
Douglas Gregorb1373d02010-01-20 20:59:29 +0000410 switch (Visitor(Cursor, Parent, ClientData)) {
411 case CXChildVisit_Break:
412 return true;
413
414 case CXChildVisit_Continue:
415 return false;
416
417 case CXChildVisit_Recurse:
418 return VisitChildren(Cursor);
419 }
420
Douglas Gregorfd643772010-01-25 16:45:46 +0000421 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000422}
423
Douglas Gregor788f5a12010-03-20 00:41:21 +0000424std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
425CursorVisitor::getPreprocessedEntities() {
426 PreprocessingRecord &PPRec
427 = *TU->getPreprocessor().getPreprocessingRecord();
428
429 bool OnlyLocalDecls
430 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
431
432 // There is no region of interest; we have to walk everything.
433 if (RegionOfInterest.isInvalid())
434 return std::make_pair(PPRec.begin(OnlyLocalDecls),
435 PPRec.end(OnlyLocalDecls));
436
437 // Find the file in which the region of interest lands.
438 SourceManager &SM = TU->getSourceManager();
439 std::pair<FileID, unsigned> Begin
440 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
441 std::pair<FileID, unsigned> End
442 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
443
444 // The region of interest spans files; we have to walk everything.
445 if (Begin.first != End.first)
446 return std::make_pair(PPRec.begin(OnlyLocalDecls),
447 PPRec.end(OnlyLocalDecls));
448
449 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
450 = TU->getPreprocessedEntitiesByFile();
451 if (ByFileMap.empty()) {
452 // Build the mapping from files to sets of preprocessed entities.
453 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
454 EEnd = PPRec.end(OnlyLocalDecls);
455 E != EEnd; ++E) {
456 std::pair<FileID, unsigned> P
457 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
458 ByFileMap[P.first].push_back(*E);
459 }
460 }
461
462 return std::make_pair(ByFileMap[Begin.first].begin(),
463 ByFileMap[Begin.first].end());
464}
465
Douglas Gregorb1373d02010-01-20 20:59:29 +0000466/// \brief Visit the children of the given cursor.
467///
468/// \returns true if the visitation should be aborted, false if it
469/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000470bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000471 if (clang_isReference(Cursor.kind)) {
472 // By definition, references have no children.
473 return false;
474 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000475
476 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000478 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000479
Douglas Gregorb1373d02010-01-20 20:59:29 +0000480 if (clang_isDeclaration(Cursor.kind)) {
481 Decl *D = getCursorDecl(Cursor);
482 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000483 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000485
Douglas Gregora59e3902010-01-21 23:27:09 +0000486 if (clang_isStatement(Cursor.kind))
487 return Visit(getCursorStmt(Cursor));
488 if (clang_isExpression(Cursor.kind))
489 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000490
Douglas Gregorb1373d02010-01-20 20:59:29 +0000491 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000492 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000493 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
494 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000495 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
496 TLEnd = CXXUnit->top_level_end();
497 TL != TLEnd; ++TL) {
498 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000499 return true;
500 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000501 } else if (VisitDeclContext(
502 CXXUnit->getASTContext().getTranslationUnitDecl()))
503 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000504
Douglas Gregor0396f462010-03-19 05:22:59 +0000505 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000506 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000507 // FIXME: Once we have the ability to deserialize a preprocessing record,
508 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000509 PreprocessingRecord::iterator E, EEnd;
510 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000511 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
512 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
513 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000514
Douglas Gregor0396f462010-03-19 05:22:59 +0000515 continue;
516 }
517
518 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
519 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
520 return true;
521
522 continue;
523 }
524 }
525 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000526 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000527 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000528
Douglas Gregorb1373d02010-01-20 20:59:29 +0000529 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000530 return false;
531}
532
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000533bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000534 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
535 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000536
Ted Kremenek664cffd2010-07-22 11:30:19 +0000537 if (Stmt *Body = B->getBody())
538 return Visit(MakeCXCursor(Body, StmtParent, TU));
539
540 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000541}
542
Douglas Gregorb1373d02010-01-20 20:59:29 +0000543bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000544 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000545 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000546
Ted Kremenek23173d72010-05-18 21:09:07 +0000547 Decl *D = *I;
548 if (D->getLexicalDeclContext() != DC)
549 continue;
550
551 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000552
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000553 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000554 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000555 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000556 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000557
558 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000559 case RangeBefore:
560 // This declaration comes before the region of interest; skip it.
561 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000562
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000563 case RangeAfter:
564 // This declaration comes after the region of interest; we're done.
565 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000566
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000567 case RangeOverlap:
568 // This declaration overlaps the region of interest; visit it.
569 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000570 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000571 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000572
Daniel Dunbard52864b2010-02-14 10:02:57 +0000573 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000574 return true;
575 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000576
Douglas Gregorb1373d02010-01-20 20:59:29 +0000577 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000578}
579
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000580bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
581 llvm_unreachable("Translation units are visited directly by Visit()");
582 return false;
583}
584
585bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
586 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
587 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000588
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000589 return false;
590}
591
592bool CursorVisitor::VisitTagDecl(TagDecl *D) {
593 return VisitDeclContext(D);
594}
595
596bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
597 if (Expr *Init = D->getInitExpr())
598 return Visit(MakeCXCursor(Init, StmtParent, TU));
599 return false;
600}
601
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000602bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
603 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
604 if (Visit(TSInfo->getTypeLoc()))
605 return true;
606
607 return false;
608}
609
Douglas Gregorb1373d02010-01-20 20:59:29 +0000610bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000611 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
612 // Visit the function declaration's syntactic components in the order
613 // written. This requires a bit of work.
614 TypeLoc TL = TSInfo->getTypeLoc();
615 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
616
617 // If we have a function declared directly (without the use of a typedef),
618 // visit just the return type. Otherwise, just visit the function's type
619 // now.
620 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
621 (!FTL && Visit(TL)))
622 return true;
623
624 // FIXME: Visit the nested-name-specifier, if present.
625
626 // Visit the declaration name.
627 if (VisitDeclarationNameInfo(ND->getNameInfo()))
628 return true;
629
630 // FIXME: Visit explicitly-specified template arguments!
631
632 // Visit the function parameters, if we have a function type.
633 if (FTL && VisitFunctionTypeLoc(*FTL, true))
634 return true;
635
636 // FIXME: Attributes?
637 }
638
Douglas Gregora59e3902010-01-21 23:27:09 +0000639 if (ND->isThisDeclarationADefinition() &&
640 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
641 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000642
Douglas Gregorb1373d02010-01-20 20:59:29 +0000643 return false;
644}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000645
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000646bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
647 if (VisitDeclaratorDecl(D))
648 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000649
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000650 if (Expr *BitWidth = D->getBitWidth())
651 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000652
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000653 return false;
654}
655
656bool CursorVisitor::VisitVarDecl(VarDecl *D) {
657 if (VisitDeclaratorDecl(D))
658 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000659
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000660 if (Expr *Init = D->getInit())
661 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000662
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000663 return false;
664}
665
666bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000667 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
668 if (Visit(TSInfo->getTypeLoc()))
669 return true;
670
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000671 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000672 PEnd = ND->param_end();
673 P != PEnd; ++P) {
674 if (Visit(MakeCXCursor(*P, TU)))
675 return true;
676 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000677
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000678 if (ND->isThisDeclarationADefinition() &&
679 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
680 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000681
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000682 return false;
683}
684
Douglas Gregora59e3902010-01-21 23:27:09 +0000685bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
686 return VisitDeclContext(D);
687}
688
Douglas Gregorb1373d02010-01-20 20:59:29 +0000689bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000690 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
691 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000692 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000693
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000694 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
695 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
696 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000697 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000698 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000699
Douglas Gregora59e3902010-01-21 23:27:09 +0000700 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000701}
702
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000703bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
704 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
705 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
706 E = PID->protocol_end(); I != E; ++I, ++PL)
707 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
708 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000709
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000710 return VisitObjCContainerDecl(PID);
711}
712
Ted Kremenek23173d72010-05-18 21:09:07 +0000713bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000714 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
715 return true;
716
Ted Kremenek23173d72010-05-18 21:09:07 +0000717 // FIXME: This implements a workaround with @property declarations also being
718 // installed in the DeclContext for the @interface. Eventually this code
719 // should be removed.
720 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
721 if (!CDecl || !CDecl->IsClassExtension())
722 return false;
723
724 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
725 if (!ID)
726 return false;
727
728 IdentifierInfo *PropertyId = PD->getIdentifier();
729 ObjCPropertyDecl *prevDecl =
730 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
731
732 if (!prevDecl)
733 return false;
734
735 // Visit synthesized methods since they will be skipped when visiting
736 // the @interface.
737 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
738 if (MD->isSynthesized())
739 if (Visit(MakeCXCursor(MD, TU)))
740 return true;
741
742 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
743 if (MD->isSynthesized())
744 if (Visit(MakeCXCursor(MD, TU)))
745 return true;
746
747 return false;
748}
749
Douglas Gregorb1373d02010-01-20 20:59:29 +0000750bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000751 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000752 if (D->getSuperClass() &&
753 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000754 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000755 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000756 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000757
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000758 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
759 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
760 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000761 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000762 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000763
Douglas Gregora59e3902010-01-21 23:27:09 +0000764 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000765}
766
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000767bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
768 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000769}
770
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000771bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000772 // 'ID' could be null when dealing with invalid code.
773 if (ObjCInterfaceDecl *ID = D->getClassInterface())
774 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
775 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000776
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000777 return VisitObjCImplDecl(D);
778}
779
780bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
781#if 0
782 // Issue callbacks for super class.
783 // FIXME: No source location information!
784 if (D->getSuperClass() &&
785 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000786 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000787 TU)))
788 return true;
789#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000790
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000791 return VisitObjCImplDecl(D);
792}
793
794bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
795 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
796 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
797 E = D->protocol_end();
798 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000799 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000800 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000801
802 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000803}
804
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
806 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
807 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
808 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000809
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000810 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000811}
812
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000813bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
814 return VisitDeclContext(D);
815}
816
Douglas Gregor01829d32010-08-31 14:41:23 +0000817bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
818 switch (Name.getName().getNameKind()) {
819 case clang::DeclarationName::Identifier:
820 case clang::DeclarationName::CXXLiteralOperatorName:
821 case clang::DeclarationName::CXXOperatorName:
822 case clang::DeclarationName::CXXUsingDirective:
823 return false;
824
825 case clang::DeclarationName::CXXConstructorName:
826 case clang::DeclarationName::CXXDestructorName:
827 case clang::DeclarationName::CXXConversionFunctionName:
828 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
829 return Visit(TSInfo->getTypeLoc());
830 return false;
831
832 case clang::DeclarationName::ObjCZeroArgSelector:
833 case clang::DeclarationName::ObjCOneArgSelector:
834 case clang::DeclarationName::ObjCMultiArgSelector:
835 // FIXME: Per-identifier location info?
836 return false;
837 }
838
839 return false;
840}
841
Ted Kremeneka0536d82010-05-07 01:04:29 +0000842bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
843 return VisitDeclContext(D);
844}
845
Douglas Gregor01829d32010-08-31 14:41:23 +0000846bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
847 return Visit(TL.getUnqualifiedLoc());
848}
849
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000850bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
851 ASTContext &Context = TU->getASTContext();
852
853 // Some builtin types (such as Objective-C's "id", "sel", and
854 // "Class") have associated declarations. Create cursors for those.
855 QualType VisitType;
856 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000857 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000858 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000859 case BuiltinType::Char_U:
860 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000861 case BuiltinType::Char16:
862 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000863 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000864 case BuiltinType::UInt:
865 case BuiltinType::ULong:
866 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000867 case BuiltinType::UInt128:
868 case BuiltinType::Char_S:
869 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000870 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000871 case BuiltinType::Short:
872 case BuiltinType::Int:
873 case BuiltinType::Long:
874 case BuiltinType::LongLong:
875 case BuiltinType::Int128:
876 case BuiltinType::Float:
877 case BuiltinType::Double:
878 case BuiltinType::LongDouble:
879 case BuiltinType::NullPtr:
880 case BuiltinType::Overload:
881 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000882 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000883
884 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000885 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000886
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000887 case BuiltinType::ObjCId:
888 VisitType = Context.getObjCIdType();
889 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000890
891 case BuiltinType::ObjCClass:
892 VisitType = Context.getObjCClassType();
893 break;
894
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000895 case BuiltinType::ObjCSel:
896 VisitType = Context.getObjCSelType();
897 break;
898 }
899
900 if (!VisitType.isNull()) {
901 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000902 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000903 TU));
904 }
905
906 return false;
907}
908
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000909bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
910 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
911}
912
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000913bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
914 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
915}
916
917bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
918 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
919}
920
921bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
922 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
923 return true;
924
John McCallc12c5bb2010-05-15 11:32:37 +0000925 return false;
926}
927
928bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
929 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
930 return true;
931
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000932 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
933 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
934 TU)))
935 return true;
936 }
937
938 return false;
939}
940
941bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +0000942 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000943}
944
945bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
946 return Visit(TL.getPointeeLoc());
947}
948
949bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
950 return Visit(TL.getPointeeLoc());
951}
952
953bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
954 return Visit(TL.getPointeeLoc());
955}
956
957bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000958 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000959}
960
961bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000962 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000963}
964
Douglas Gregor01829d32010-08-31 14:41:23 +0000965bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
966 bool SkipResultType) {
967 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000968 return true;
969
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000970 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000971 if (Decl *D = TL.getArg(I))
972 if (Visit(MakeCXCursor(D, TU)))
973 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000974
975 return false;
976}
977
978bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
979 if (Visit(TL.getElementLoc()))
980 return true;
981
982 if (Expr *Size = TL.getSizeExpr())
983 return Visit(MakeCXCursor(Size, StmtParent, TU));
984
985 return false;
986}
987
Douglas Gregor2332c112010-01-21 20:48:56 +0000988bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
989 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
990}
991
992bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
993 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
994 return Visit(TSInfo->getTypeLoc());
995
996 return false;
997}
998
Douglas Gregora59e3902010-01-21 23:27:09 +0000999bool CursorVisitor::VisitStmt(Stmt *S) {
1000 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1001 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001002 if (Stmt *C = *Child)
1003 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1004 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001005 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001006
Douglas Gregora59e3902010-01-21 23:27:09 +00001007 return false;
1008}
1009
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001010bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1011 // Specially handle CaseStmts because they can be nested, e.g.:
1012 //
1013 // case 1:
1014 // case 2:
1015 //
1016 // In this case the second CaseStmt is the child of the first. Walking
1017 // these recursively can blow out the stack.
1018 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1019 while (true) {
1020 // Set the Parent field to Cursor, then back to its old value once we're
1021 // done.
1022 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1023
1024 if (Stmt *LHS = S->getLHS())
1025 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1026 return true;
1027 if (Stmt *RHS = S->getRHS())
1028 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1029 return true;
1030 if (Stmt *SubStmt = S->getSubStmt()) {
1031 if (!isa<CaseStmt>(SubStmt))
1032 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1033
1034 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1035 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1036 Cursor = MakeCXCursor(CS, StmtParent, TU);
1037 if (RegionOfInterest.isValid()) {
1038 SourceRange Range = CS->getSourceRange();
1039 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1040 return false;
1041 }
1042
1043 switch (Visitor(Cursor, Parent, ClientData)) {
1044 case CXChildVisit_Break: return true;
1045 case CXChildVisit_Continue: return false;
1046 case CXChildVisit_Recurse:
1047 // Perform tail-recursion manually.
1048 S = CS;
1049 continue;
1050 }
1051 }
1052 return false;
1053 }
1054}
1055
Douglas Gregora59e3902010-01-21 23:27:09 +00001056bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1057 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1058 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001059 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001060 return true;
1061 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001062
Douglas Gregora59e3902010-01-21 23:27:09 +00001063 return false;
1064}
1065
Douglas Gregorf5bab412010-01-22 01:00:11 +00001066bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1067 if (VarDecl *Var = S->getConditionVariable()) {
1068 if (Visit(MakeCXCursor(Var, TU)))
1069 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001070 }
1071
Douglas Gregor263b47b2010-01-25 16:12:32 +00001072 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1073 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001074 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1075 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001076 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1077 return true;
1078
1079 return false;
1080}
1081
1082bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1083 if (VarDecl *Var = S->getConditionVariable()) {
1084 if (Visit(MakeCXCursor(Var, TU)))
1085 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001086 }
1087
Douglas Gregor263b47b2010-01-25 16:12:32 +00001088 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1089 return true;
1090 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1091 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001092
Douglas Gregor263b47b2010-01-25 16:12:32 +00001093 return false;
1094}
1095
1096bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1097 if (VarDecl *Var = S->getConditionVariable()) {
1098 if (Visit(MakeCXCursor(Var, TU)))
1099 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001100 }
1101
Douglas Gregor263b47b2010-01-25 16:12:32 +00001102 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1103 return true;
1104 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001105 return true;
1106
Douglas Gregor263b47b2010-01-25 16:12:32 +00001107 return false;
1108}
1109
1110bool CursorVisitor::VisitForStmt(ForStmt *S) {
1111 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1112 return true;
1113 if (VarDecl *Var = S->getConditionVariable()) {
1114 if (Visit(MakeCXCursor(Var, TU)))
1115 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001116 }
1117
Douglas Gregor263b47b2010-01-25 16:12:32 +00001118 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1119 return true;
1120 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1121 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001122 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1123 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001124
Douglas Gregorf5bab412010-01-22 01:00:11 +00001125 return false;
1126}
1127
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001128bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1129 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1130 return true;
1131
1132 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1133 return true;
1134
1135 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1136 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1137 return true;
1138
1139 return false;
1140}
1141
Ted Kremenek3064ef92010-08-27 21:34:58 +00001142bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1143 if (D->isDefinition()) {
1144 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1145 E = D->bases_end(); I != E; ++I) {
1146 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1147 return true;
1148 }
1149 }
1150
1151 return VisitTagDecl(D);
1152}
1153
1154
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001155bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1156 return Visit(B->getBlockDecl());
1157}
1158
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001159bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1160 // FIXME: Visit fields as well?
1161 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1162 return true;
1163
1164 return VisitExpr(E);
1165}
1166
Douglas Gregor336fd812010-01-23 00:40:08 +00001167bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1168 if (E->isArgumentType()) {
1169 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1170 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001171
Douglas Gregor336fd812010-01-23 00:40:08 +00001172 return false;
1173 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001174
Douglas Gregor336fd812010-01-23 00:40:08 +00001175 return VisitExpr(E);
1176}
1177
1178bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1179 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1180 if (Visit(TSInfo->getTypeLoc()))
1181 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001182
Douglas Gregor336fd812010-01-23 00:40:08 +00001183 return VisitCastExpr(E);
1184}
1185
1186bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1187 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1188 if (Visit(TSInfo->getTypeLoc()))
1189 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001190
Douglas Gregor336fd812010-01-23 00:40:08 +00001191 return VisitExpr(E);
1192}
1193
Douglas Gregor648220e2010-08-10 15:02:34 +00001194bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1195 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1196 Visit(E->getArgTInfo2()->getTypeLoc());
1197}
1198
1199bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1200 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1201 return true;
1202
1203 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1204}
1205
Douglas Gregorc2350e52010-03-08 16:40:19 +00001206bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001207 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1208 if (Visit(TSInfo->getTypeLoc()))
1209 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001210
1211 return VisitExpr(E);
1212}
1213
Douglas Gregor81d34662010-04-20 15:39:42 +00001214bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1215 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1216}
1217
1218
Ted Kremenek09dfa372010-02-18 05:46:33 +00001219bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001220 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1221 i != e; ++i)
1222 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001223 return true;
1224
1225 return false;
1226}
1227
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001228extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001229CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1230 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001231 // We use crash recovery to make some of our APIs more reliable, implicitly
1232 // enable it.
1233 llvm::CrashRecoveryContext::Enable();
1234
Douglas Gregora030b7c2010-01-22 20:35:53 +00001235 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001236 if (excludeDeclarationsFromPCH)
1237 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001238 if (displayDiagnostics)
1239 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001240 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001241}
1242
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001243void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001244 if (CIdx)
1245 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001246 if (getenv("LIBCLANG_TIMING"))
1247 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001248}
1249
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001250void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001251 if (CIdx) {
1252 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1253 CXXIdx->setUseExternalASTGeneration(value);
1254 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001255}
1256
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001257CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001258 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001259 if (!CIdx)
1260 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001261
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001262 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001263
Douglas Gregor28019772010-04-05 23:52:57 +00001264 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001265 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001266 CXXIdx->getOnlyLocalDecls(),
1267 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001268}
1269
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001270unsigned clang_defaultEditingTranslationUnitOptions() {
1271 return CXTranslationUnit_PrecompiledPreamble;
1272}
1273
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001274CXTranslationUnit
1275clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1276 const char *source_filename,
1277 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001278 const char **command_line_args,
1279 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001280 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001281 return clang_parseTranslationUnit(CIdx, source_filename,
1282 command_line_args, num_command_line_args,
1283 unsaved_files, num_unsaved_files,
1284 CXTranslationUnit_DetailedPreprocessingRecord);
1285}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001286
1287struct ParseTranslationUnitInfo {
1288 CXIndex CIdx;
1289 const char *source_filename;
1290 const char **command_line_args;
1291 int num_command_line_args;
1292 struct CXUnsavedFile *unsaved_files;
1293 unsigned num_unsaved_files;
1294 unsigned options;
1295 CXTranslationUnit result;
1296};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001297static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001298 ParseTranslationUnitInfo *PTUI =
1299 static_cast<ParseTranslationUnitInfo*>(UserData);
1300 CXIndex CIdx = PTUI->CIdx;
1301 const char *source_filename = PTUI->source_filename;
1302 const char **command_line_args = PTUI->command_line_args;
1303 int num_command_line_args = PTUI->num_command_line_args;
1304 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1305 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1306 unsigned options = PTUI->options;
1307 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001308
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001309 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001310 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001311
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001312 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1313
Douglas Gregor44c181a2010-07-23 00:33:23 +00001314 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001315 bool CompleteTranslationUnit
1316 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001317 bool CacheCodeCompetionResults
1318 = options & CXTranslationUnit_CacheCompletionResults;
1319
Douglas Gregor5352ac02010-01-28 00:27:43 +00001320 // Configure the diagnostics.
1321 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001322 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1323 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001324
Douglas Gregor4db64a42010-01-23 00:14:00 +00001325 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1326 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001327 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001328 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001329 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001330 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1331 Buffer));
1332 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001333
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001334 if (!CXXIdx->getUseExternalASTGeneration()) {
1335 llvm::SmallVector<const char *, 16> Args;
1336
1337 // The 'source_filename' argument is optional. If the caller does not
1338 // specify it then it is assumed that the source file is specified
1339 // in the actual argument list.
1340 if (source_filename)
1341 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001342
1343 // Since the Clang C library is primarily used by batch tools dealing with
1344 // (often very broken) source code, where spell-checking can have a
1345 // significant negative impact on performance (particularly when
1346 // precompiled headers are involved), we disable it by default.
1347 // Note that we place this argument early in the list, so that it can be
1348 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001349 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001350
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001351 Args.insert(Args.end(), command_line_args,
1352 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001353
Douglas Gregor44c181a2010-07-23 00:33:23 +00001354 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001355 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1356 Args.push_back("-Xclang");
1357 Args.push_back("-detailed-preprocessing-record");
1358 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001359
Douglas Gregor5352ac02010-01-28 00:27:43 +00001360 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001361
Ted Kremenek29b72842010-01-07 22:49:05 +00001362#ifdef USE_CRASHTRACER
1363 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001364#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001365
Daniel Dunbar94220972009-12-05 02:17:18 +00001366 llvm::OwningPtr<ASTUnit> Unit(
1367 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001368 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001369 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001370 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001371 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001372 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001373 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001374 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001375 CompleteTranslationUnit,
1376 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001377
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001378 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001379 // Make sure to check that 'Unit' is non-NULL.
1380 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001381 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1382 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001383 D != DEnd; ++D) {
1384 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001385 CXString Msg = clang_formatDiagnostic(&Diag,
1386 clang_defaultDiagnosticDisplayOptions());
1387 fprintf(stderr, "%s\n", clang_getCString(Msg));
1388 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001389 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001390#ifdef LLVM_ON_WIN32
1391 // On Windows, force a flush, since there may be multiple copies of
1392 // stderr and stdout in the file system, all with different buffers
1393 // but writing to the same device.
1394 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001395#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001396 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001397 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001398
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001399 PTUI->result = Unit.take();
1400 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001401 }
1402
Ted Kremenek139ba862009-10-22 00:03:57 +00001403 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001404 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001405
Ted Kremenek139ba862009-10-22 00:03:57 +00001406 // First add the complete path to the 'clang' executable.
1407 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001408 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001409
Ted Kremenek139ba862009-10-22 00:03:57 +00001410 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001411 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001412
Ted Kremenek139ba862009-10-22 00:03:57 +00001413 // The 'source_filename' argument is optional. If the caller does not
1414 // specify it then it is assumed that the source file is specified
1415 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001416 if (source_filename)
1417 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001418
Steve Naroff37b5ac22009-10-15 20:50:09 +00001419 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001420 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001421 char astTmpFile[L_tmpnam];
1422 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001423
1424 // Since the Clang C library is primarily used by batch tools dealing with
1425 // (often very broken) source code, where spell-checking can have a
1426 // significant negative impact on performance (particularly when
1427 // precompiled headers are involved), we disable it by default.
1428 // Note that we place this argument early in the list, so that it can be
1429 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001430 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001431
Douglas Gregor4db64a42010-01-23 00:14:00 +00001432 // Remap any unsaved files to temporary files.
1433 std::vector<llvm::sys::Path> TemporaryFiles;
1434 std::vector<std::string> RemapArgs;
1435 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001436 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001437
Douglas Gregor4db64a42010-01-23 00:14:00 +00001438 // The pointers into the elements of RemapArgs are stable because we
1439 // won't be adding anything to RemapArgs after this point.
1440 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1441 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001442
Ted Kremenek139ba862009-10-22 00:03:57 +00001443 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1444 for (int i = 0; i < num_command_line_args; ++i)
1445 if (const char *arg = command_line_args[i]) {
1446 if (strcmp(arg, "-o") == 0) {
1447 ++i; // Also skip the matching argument.
1448 continue;
1449 }
1450 if (strcmp(arg, "-emit-ast") == 0 ||
1451 strcmp(arg, "-c") == 0 ||
1452 strcmp(arg, "-fsyntax-only") == 0) {
1453 continue;
1454 }
1455
1456 // Keep the argument.
1457 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001458 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001459
Douglas Gregord93256e2010-01-28 06:00:51 +00001460 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001461 char tmpFileResults[L_tmpnam];
1462 char *tmpResultsFileName = tmpnam(tmpFileResults);
1463 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001464 TemporaryFiles.push_back(DiagnosticsFile);
1465 argv.push_back("-fdiagnostics-binary");
1466
Douglas Gregor44c181a2010-07-23 00:33:23 +00001467 // Do we need the detailed preprocessing record?
1468 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1469 argv.push_back("-Xclang");
1470 argv.push_back("-detailed-preprocessing-record");
1471 }
1472
Ted Kremenek139ba862009-10-22 00:03:57 +00001473 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001474 argv.push_back(NULL);
1475
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001476 // Invoke 'clang'.
1477 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1478 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001479 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001480 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1481 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001482 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001483 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001484 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001485
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001486 if (!ErrMsg.empty()) {
1487 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001488 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001489 I != E; ++I) {
1490 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001491 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001492 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001493 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001494
Daniel Dunbar32141c82010-02-23 20:23:45 +00001495 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001496 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001497
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001498 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001499 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001500 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001501 RemappedFiles.size(),
1502 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001503 if (ATU) {
1504 LoadSerializedDiagnostics(DiagnosticsFile,
1505 num_unsaved_files, unsaved_files,
1506 ATU->getFileManager(),
1507 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001508 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001509 } else if (CXXIdx->getDisplayDiagnostics()) {
1510 // We failed to load the ASTUnit, but we can still deserialize the
1511 // diagnostics and emit them.
1512 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001513 Diagnostic Diag;
1514 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001515 // FIXME: Faked LangOpts!
1516 LangOptions LangOpts;
1517 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1518 LoadSerializedDiagnostics(DiagnosticsFile,
1519 num_unsaved_files, unsaved_files,
1520 FileMgr, SourceMgr, Diags);
1521 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1522 DEnd = Diags.end();
1523 D != DEnd; ++D) {
1524 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001525 CXString Msg = clang_formatDiagnostic(&Diag,
1526 clang_defaultDiagnosticDisplayOptions());
1527 fprintf(stderr, "%s\n", clang_getCString(Msg));
1528 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001529 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001530
1531#ifdef LLVM_ON_WIN32
1532 // On Windows, force a flush, since there may be multiple copies of
1533 // stderr and stdout in the file system, all with different buffers
1534 // but writing to the same device.
1535 fflush(stderr);
1536#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001537 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001538
Douglas Gregor313e26c2010-02-18 23:35:40 +00001539 if (ATU) {
1540 // Make the translation unit responsible for destroying all temporary files.
1541 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1542 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001543 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001544 } else {
1545 // Destroy all of the temporary files now; they can't be referenced any
1546 // longer.
1547 llvm::sys::Path(astTmpFile).eraseFromDisk();
1548 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1549 TemporaryFiles[i].eraseFromDisk();
1550 }
1551
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001552 PTUI->result = ATU;
1553}
1554CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1555 const char *source_filename,
1556 const char **command_line_args,
1557 int num_command_line_args,
1558 struct CXUnsavedFile *unsaved_files,
1559 unsigned num_unsaved_files,
1560 unsigned options) {
1561 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1562 num_command_line_args, unsaved_files, num_unsaved_files,
1563 options, 0 };
1564 llvm::CrashRecoveryContext CRC;
1565
1566 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001567 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1568 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1569 fprintf(stderr, " 'command_line_args' : [");
1570 for (int i = 0; i != num_command_line_args; ++i) {
1571 if (i)
1572 fprintf(stderr, ", ");
1573 fprintf(stderr, "'%s'", command_line_args[i]);
1574 }
1575 fprintf(stderr, "],\n");
1576 fprintf(stderr, " 'unsaved_files' : [");
1577 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1578 if (i)
1579 fprintf(stderr, ", ");
1580 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1581 unsaved_files[i].Length);
1582 }
1583 fprintf(stderr, "],\n");
1584 fprintf(stderr, " 'options' : %d,\n", options);
1585 fprintf(stderr, "}\n");
1586
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001587 return 0;
1588 }
1589
1590 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001591}
1592
Douglas Gregor19998442010-08-13 15:35:05 +00001593unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1594 return CXSaveTranslationUnit_None;
1595}
1596
1597int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1598 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001599 if (!TU)
1600 return 1;
1601
1602 return static_cast<ASTUnit *>(TU)->Save(FileName);
1603}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001604
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001605void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001606 if (CTUnit) {
1607 // If the translation unit has been marked as unsafe to free, just discard
1608 // it.
1609 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1610 return;
1611
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001612 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001613 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001614}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001615
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001616unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1617 return CXReparse_None;
1618}
1619
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001620struct ReparseTranslationUnitInfo {
1621 CXTranslationUnit TU;
1622 unsigned num_unsaved_files;
1623 struct CXUnsavedFile *unsaved_files;
1624 unsigned options;
1625 int result;
1626};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001627static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001628 ReparseTranslationUnitInfo *RTUI =
1629 static_cast<ReparseTranslationUnitInfo*>(UserData);
1630 CXTranslationUnit TU = RTUI->TU;
1631 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1632 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1633 unsigned options = RTUI->options;
1634 (void) options;
1635 RTUI->result = 1;
1636
Douglas Gregorabc563f2010-07-19 21:46:24 +00001637 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001638 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001639
1640 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1641 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1642 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1643 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001644 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001645 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1646 Buffer));
1647 }
1648
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001649 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1650 RemappedFiles.size()))
1651 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001652}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001653int clang_reparseTranslationUnit(CXTranslationUnit TU,
1654 unsigned num_unsaved_files,
1655 struct CXUnsavedFile *unsaved_files,
1656 unsigned options) {
1657 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1658 options, 0 };
1659 llvm::CrashRecoveryContext CRC;
1660
1661 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001662 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001663 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1664 return 1;
1665 }
1666
1667 return RTUI.result;
1668}
1669
Douglas Gregordf95a132010-08-09 20:45:32 +00001670
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001671CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001672 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001673 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001674
Steve Naroff77accc12009-09-03 18:19:54 +00001675 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001676 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001677}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001678
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001679CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001680 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001681 return Result;
1682}
1683
Ted Kremenekfb480492010-01-13 21:46:36 +00001684} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001685
Ted Kremenekfb480492010-01-13 21:46:36 +00001686//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001687// CXSourceLocation and CXSourceRange Operations.
1688//===----------------------------------------------------------------------===//
1689
Douglas Gregorb9790342010-01-22 21:44:22 +00001690extern "C" {
1691CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001692 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001693 return Result;
1694}
1695
1696unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001697 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1698 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1699 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001700}
1701
1702CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1703 CXFile file,
1704 unsigned line,
1705 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001706 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001707 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001708
Douglas Gregorb9790342010-01-22 21:44:22 +00001709 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1710 SourceLocation SLoc
1711 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001712 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001713 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001714
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001715 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001716}
1717
Douglas Gregor5352ac02010-01-28 00:27:43 +00001718CXSourceRange clang_getNullRange() {
1719 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1720 return Result;
1721}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001722
Douglas Gregor5352ac02010-01-28 00:27:43 +00001723CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1724 if (begin.ptr_data[0] != end.ptr_data[0] ||
1725 begin.ptr_data[1] != end.ptr_data[1])
1726 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001727
1728 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001729 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001730 return Result;
1731}
1732
Douglas Gregor46766dc2010-01-26 19:19:08 +00001733void clang_getInstantiationLocation(CXSourceLocation location,
1734 CXFile *file,
1735 unsigned *line,
1736 unsigned *column,
1737 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001738 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1739
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001740 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001741 if (file)
1742 *file = 0;
1743 if (line)
1744 *line = 0;
1745 if (column)
1746 *column = 0;
1747 if (offset)
1748 *offset = 0;
1749 return;
1750 }
1751
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001752 const SourceManager &SM =
1753 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001754 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001755
1756 if (file)
1757 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1758 if (line)
1759 *line = SM.getInstantiationLineNumber(InstLoc);
1760 if (column)
1761 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001762 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001763 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001764}
1765
Douglas Gregor1db19de2010-01-19 21:36:55 +00001766CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001767 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001768 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001769 return Result;
1770}
1771
1772CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001773 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001774 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001775 return Result;
1776}
1777
Douglas Gregorb9790342010-01-22 21:44:22 +00001778} // end: extern "C"
1779
Douglas Gregor1db19de2010-01-19 21:36:55 +00001780//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001781// CXFile Operations.
1782//===----------------------------------------------------------------------===//
1783
1784extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001785CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001786 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001787 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001788
Steve Naroff88145032009-10-27 14:35:18 +00001789 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001790 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001791}
1792
1793time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001794 if (!SFile)
1795 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001796
Steve Naroff88145032009-10-27 14:35:18 +00001797 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1798 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001799}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001800
Douglas Gregorb9790342010-01-22 21:44:22 +00001801CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1802 if (!tu)
1803 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001804
Douglas Gregorb9790342010-01-22 21:44:22 +00001805 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001806
Douglas Gregorb9790342010-01-22 21:44:22 +00001807 FileManager &FMgr = CXXUnit->getFileManager();
1808 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1809 return const_cast<FileEntry *>(File);
1810}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001811
Ted Kremenekfb480492010-01-13 21:46:36 +00001812} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001813
Ted Kremenekfb480492010-01-13 21:46:36 +00001814//===----------------------------------------------------------------------===//
1815// CXCursor Operations.
1816//===----------------------------------------------------------------------===//
1817
Ted Kremenekfb480492010-01-13 21:46:36 +00001818static Decl *getDeclFromExpr(Stmt *E) {
1819 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1820 return RefExpr->getDecl();
1821 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1822 return ME->getMemberDecl();
1823 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1824 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001825
Ted Kremenekfb480492010-01-13 21:46:36 +00001826 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1827 return getDeclFromExpr(CE->getCallee());
1828 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1829 return getDeclFromExpr(CE->getSubExpr());
1830 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1831 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001832
Ted Kremenekfb480492010-01-13 21:46:36 +00001833 return 0;
1834}
1835
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001836static SourceLocation getLocationFromExpr(Expr *E) {
1837 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1838 return /*FIXME:*/Msg->getLeftLoc();
1839 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1840 return DRE->getLocation();
1841 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1842 return Member->getMemberLoc();
1843 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1844 return Ivar->getLocation();
1845 return E->getLocStart();
1846}
1847
Ted Kremenekfb480492010-01-13 21:46:36 +00001848extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001849
1850unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001851 CXCursorVisitor visitor,
1852 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001853 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001854
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001855 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1856 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00001857 return CursorVis.VisitChildren(parent);
1858}
1859
Douglas Gregor78205d42010-01-20 21:45:58 +00001860static CXString getDeclSpelling(Decl *D) {
1861 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1862 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001863 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001864
Douglas Gregor78205d42010-01-20 21:45:58 +00001865 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001866 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001867
Douglas Gregor78205d42010-01-20 21:45:58 +00001868 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1869 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1870 // and returns different names. NamedDecl returns the class name and
1871 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001872 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001873
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001874 llvm::SmallString<1024> S;
1875 llvm::raw_svector_ostream os(S);
1876 ND->printName(os);
1877
1878 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001879}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001880
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001881CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001882 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001883 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001884
Steve Narofff334b4e2009-09-02 18:26:48 +00001885 if (clang_isReference(C.kind)) {
1886 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001887 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001888 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001889 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001890 }
1891 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001892 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001893 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001894 }
1895 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001896 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001897 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001898 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001899 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00001900 case CXCursor_CXXBaseSpecifier: {
1901 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
1902 return createCXString(B->getType().getAsString());
1903 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001904 case CXCursor_TypeRef: {
1905 TypeDecl *Type = getCursorTypeRef(C).first;
1906 assert(Type && "Missing type decl");
1907
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001908 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1909 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001910 }
1911
Daniel Dunbaracca7252009-11-30 20:42:49 +00001912 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001913 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001914 }
1915 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001916
1917 if (clang_isExpression(C.kind)) {
1918 Decl *D = getDeclFromExpr(getCursorExpr(C));
1919 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001920 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001921 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001922 }
1923
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001924 if (C.kind == CXCursor_MacroInstantiation)
1925 return createCXString(getCursorMacroInstantiation(C)->getName()
1926 ->getNameStart());
1927
Douglas Gregor572feb22010-03-18 18:04:21 +00001928 if (C.kind == CXCursor_MacroDefinition)
1929 return createCXString(getCursorMacroDefinition(C)->getName()
1930 ->getNameStart());
1931
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001932 if (clang_isDeclaration(C.kind))
1933 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001934
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001935 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001936}
1937
Ted Kremeneke68fff62010-02-17 00:41:32 +00001938CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001939 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001940 case CXCursor_FunctionDecl:
1941 return createCXString("FunctionDecl");
1942 case CXCursor_TypedefDecl:
1943 return createCXString("TypedefDecl");
1944 case CXCursor_EnumDecl:
1945 return createCXString("EnumDecl");
1946 case CXCursor_EnumConstantDecl:
1947 return createCXString("EnumConstantDecl");
1948 case CXCursor_StructDecl:
1949 return createCXString("StructDecl");
1950 case CXCursor_UnionDecl:
1951 return createCXString("UnionDecl");
1952 case CXCursor_ClassDecl:
1953 return createCXString("ClassDecl");
1954 case CXCursor_FieldDecl:
1955 return createCXString("FieldDecl");
1956 case CXCursor_VarDecl:
1957 return createCXString("VarDecl");
1958 case CXCursor_ParmDecl:
1959 return createCXString("ParmDecl");
1960 case CXCursor_ObjCInterfaceDecl:
1961 return createCXString("ObjCInterfaceDecl");
1962 case CXCursor_ObjCCategoryDecl:
1963 return createCXString("ObjCCategoryDecl");
1964 case CXCursor_ObjCProtocolDecl:
1965 return createCXString("ObjCProtocolDecl");
1966 case CXCursor_ObjCPropertyDecl:
1967 return createCXString("ObjCPropertyDecl");
1968 case CXCursor_ObjCIvarDecl:
1969 return createCXString("ObjCIvarDecl");
1970 case CXCursor_ObjCInstanceMethodDecl:
1971 return createCXString("ObjCInstanceMethodDecl");
1972 case CXCursor_ObjCClassMethodDecl:
1973 return createCXString("ObjCClassMethodDecl");
1974 case CXCursor_ObjCImplementationDecl:
1975 return createCXString("ObjCImplementationDecl");
1976 case CXCursor_ObjCCategoryImplDecl:
1977 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00001978 case CXCursor_CXXMethod:
1979 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001980 case CXCursor_UnexposedDecl:
1981 return createCXString("UnexposedDecl");
1982 case CXCursor_ObjCSuperClassRef:
1983 return createCXString("ObjCSuperClassRef");
1984 case CXCursor_ObjCProtocolRef:
1985 return createCXString("ObjCProtocolRef");
1986 case CXCursor_ObjCClassRef:
1987 return createCXString("ObjCClassRef");
1988 case CXCursor_TypeRef:
1989 return createCXString("TypeRef");
1990 case CXCursor_UnexposedExpr:
1991 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001992 case CXCursor_BlockExpr:
1993 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001994 case CXCursor_DeclRefExpr:
1995 return createCXString("DeclRefExpr");
1996 case CXCursor_MemberRefExpr:
1997 return createCXString("MemberRefExpr");
1998 case CXCursor_CallExpr:
1999 return createCXString("CallExpr");
2000 case CXCursor_ObjCMessageExpr:
2001 return createCXString("ObjCMessageExpr");
2002 case CXCursor_UnexposedStmt:
2003 return createCXString("UnexposedStmt");
2004 case CXCursor_InvalidFile:
2005 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002006 case CXCursor_InvalidCode:
2007 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002008 case CXCursor_NoDeclFound:
2009 return createCXString("NoDeclFound");
2010 case CXCursor_NotImplemented:
2011 return createCXString("NotImplemented");
2012 case CXCursor_TranslationUnit:
2013 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002014 case CXCursor_UnexposedAttr:
2015 return createCXString("UnexposedAttr");
2016 case CXCursor_IBActionAttr:
2017 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002018 case CXCursor_IBOutletAttr:
2019 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002020 case CXCursor_IBOutletCollectionAttr:
2021 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002022 case CXCursor_PreprocessingDirective:
2023 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002024 case CXCursor_MacroDefinition:
2025 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002026 case CXCursor_MacroInstantiation:
2027 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002028 case CXCursor_Namespace:
2029 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002030 case CXCursor_LinkageSpec:
2031 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002032 case CXCursor_CXXBaseSpecifier:
2033 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002034 case CXCursor_Constructor:
2035 return createCXString("CXXConstructor");
2036 case CXCursor_Destructor:
2037 return createCXString("CXXDestructor");
2038 case CXCursor_ConversionFunction:
2039 return createCXString("CXXConversion");
Steve Naroff89922f82009-08-31 00:59:03 +00002040 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002041
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002042 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002043 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002044}
Steve Naroff89922f82009-08-31 00:59:03 +00002045
Ted Kremeneke68fff62010-02-17 00:41:32 +00002046enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2047 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002048 CXClientData client_data) {
2049 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2050 *BestCursor = cursor;
2051 return CXChildVisit_Recurse;
2052}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002053
Douglas Gregorb9790342010-01-22 21:44:22 +00002054CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2055 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002056 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002057
Douglas Gregorb9790342010-01-22 21:44:22 +00002058 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002059 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2060
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002061 // Translate the given source location to make it point at the beginning of
2062 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002063 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002064
2065 // Guard against an invalid SourceLocation, or we may assert in one
2066 // of the following calls.
2067 if (SLoc.isInvalid())
2068 return clang_getNullCursor();
2069
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002070 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2071 CXXUnit->getASTContext().getLangOptions());
2072
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002073 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2074 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002075 // FIXME: Would be great to have a "hint" cursor, then walk from that
2076 // hint cursor upward until we find a cursor whose source range encloses
2077 // the region of interest, rather than starting from the translation unit.
2078 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002079 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002080 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002081 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002082 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002083 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002084}
2085
Ted Kremenek73885552009-11-17 19:28:59 +00002086CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002087 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002088}
2089
2090unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002091 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002092}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002093
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002094unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002095 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2096}
2097
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002098unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002099 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2100}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002101
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002102unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002103 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2104}
2105
Douglas Gregor97b98722010-01-19 23:20:36 +00002106unsigned clang_isExpression(enum CXCursorKind K) {
2107 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2108}
2109
2110unsigned clang_isStatement(enum CXCursorKind K) {
2111 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2112}
2113
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002114unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2115 return K == CXCursor_TranslationUnit;
2116}
2117
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002118unsigned clang_isPreprocessing(enum CXCursorKind K) {
2119 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2120}
2121
Ted Kremenekad6eff62010-03-08 21:17:29 +00002122unsigned clang_isUnexposed(enum CXCursorKind K) {
2123 switch (K) {
2124 case CXCursor_UnexposedDecl:
2125 case CXCursor_UnexposedExpr:
2126 case CXCursor_UnexposedStmt:
2127 case CXCursor_UnexposedAttr:
2128 return true;
2129 default:
2130 return false;
2131 }
2132}
2133
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002134CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002135 return C.kind;
2136}
2137
Douglas Gregor98258af2010-01-18 22:46:11 +00002138CXSourceLocation clang_getCursorLocation(CXCursor C) {
2139 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002140 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002141 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002142 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2143 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002144 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002145 }
2146
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002147 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002148 std::pair<ObjCProtocolDecl *, SourceLocation> P
2149 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002150 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002151 }
2152
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002153 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002154 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2155 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002156 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002157 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002158
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002159 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002160 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002161 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002162 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002163
2164 case CXCursor_CXXBaseSpecifier: {
2165 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2166 return clang_getNullLocation();
2167 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002168
Douglas Gregorf46034a2010-01-18 23:41:10 +00002169 default:
2170 // FIXME: Need a way to enumerate all non-reference cases.
2171 llvm_unreachable("Missed a reference kind");
2172 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002173 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002174
2175 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002176 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002177 getLocationFromExpr(getCursorExpr(C)));
2178
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002179 if (C.kind == CXCursor_PreprocessingDirective) {
2180 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2181 return cxloc::translateSourceLocation(getCursorContext(C), L);
2182 }
Douglas Gregor48072312010-03-18 15:23:44 +00002183
2184 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002185 SourceLocation L
2186 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002187 return cxloc::translateSourceLocation(getCursorContext(C), L);
2188 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002189
2190 if (C.kind == CXCursor_MacroDefinition) {
2191 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2192 return cxloc::translateSourceLocation(getCursorContext(C), L);
2193 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002194
Ted Kremenek9a700d22010-05-12 06:16:13 +00002195 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002196 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002197
Douglas Gregorf46034a2010-01-18 23:41:10 +00002198 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002199 SourceLocation Loc = D->getLocation();
2200 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2201 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002202 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002203}
Douglas Gregora7bde202010-01-19 00:34:46 +00002204
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002205} // end extern "C"
2206
2207static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002208 if (clang_isReference(C.kind)) {
2209 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002210 case CXCursor_ObjCSuperClassRef:
2211 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002212
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002213 case CXCursor_ObjCProtocolRef:
2214 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002215
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002216 case CXCursor_ObjCClassRef:
2217 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002218
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002219 case CXCursor_TypeRef:
2220 return getCursorTypeRef(C).second;
Ted Kremenek3064ef92010-08-27 21:34:58 +00002221
2222 case CXCursor_CXXBaseSpecifier:
2223 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2224 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002225
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002226 default:
2227 // FIXME: Need a way to enumerate all non-reference cases.
2228 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002229 }
2230 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002231
2232 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002233 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002234
2235 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002236 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002237
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002238 if (C.kind == CXCursor_PreprocessingDirective)
2239 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002240
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002241 if (C.kind == CXCursor_MacroInstantiation)
2242 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002243
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002244 if (C.kind == CXCursor_MacroDefinition)
2245 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002246
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002247 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2248 return getCursorDecl(C)->getSourceRange();
2249
2250 return SourceRange();
2251}
2252
2253extern "C" {
2254
2255CXSourceRange clang_getCursorExtent(CXCursor C) {
2256 SourceRange R = getRawCursorExtent(C);
2257 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002258 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002259
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002260 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002261}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002262
2263CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002264 if (clang_isInvalid(C.kind))
2265 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002266
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002267 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002268 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002269 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002270
Douglas Gregor97b98722010-01-19 23:20:36 +00002271 if (clang_isExpression(C.kind)) {
2272 Decl *D = getDeclFromExpr(getCursorExpr(C));
2273 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002274 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002275 return clang_getNullCursor();
2276 }
2277
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002278 if (C.kind == CXCursor_MacroInstantiation) {
2279 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2280 return MakeMacroDefinitionCursor(Def, CXXUnit);
2281 }
2282
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002283 if (!clang_isReference(C.kind))
2284 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002285
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002286 switch (C.kind) {
2287 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002288 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002289
2290 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002291 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002292
2293 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002294 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002295
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002296 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002297 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenek3064ef92010-08-27 21:34:58 +00002298
2299 case CXCursor_CXXBaseSpecifier: {
2300 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2301 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2302 CXXUnit));
2303 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002304
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002305 default:
2306 // We would prefer to enumerate all non-reference cursor kinds here.
2307 llvm_unreachable("Unhandled reference cursor kind");
2308 break;
2309 }
2310 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002311
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002312 return clang_getNullCursor();
2313}
2314
Douglas Gregorb6998662010-01-19 19:34:47 +00002315CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002316 if (clang_isInvalid(C.kind))
2317 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002318
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002319 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002320
Douglas Gregorb6998662010-01-19 19:34:47 +00002321 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002322 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002323 C = clang_getCursorReferenced(C);
2324 WasReference = true;
2325 }
2326
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002327 if (C.kind == CXCursor_MacroInstantiation)
2328 return clang_getCursorReferenced(C);
2329
Douglas Gregorb6998662010-01-19 19:34:47 +00002330 if (!clang_isDeclaration(C.kind))
2331 return clang_getNullCursor();
2332
2333 Decl *D = getCursorDecl(C);
2334 if (!D)
2335 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002336
Douglas Gregorb6998662010-01-19 19:34:47 +00002337 switch (D->getKind()) {
2338 // Declaration kinds that don't really separate the notions of
2339 // declaration and definition.
2340 case Decl::Namespace:
2341 case Decl::Typedef:
2342 case Decl::TemplateTypeParm:
2343 case Decl::EnumConstant:
2344 case Decl::Field:
2345 case Decl::ObjCIvar:
2346 case Decl::ObjCAtDefsField:
2347 case Decl::ImplicitParam:
2348 case Decl::ParmVar:
2349 case Decl::NonTypeTemplateParm:
2350 case Decl::TemplateTemplateParm:
2351 case Decl::ObjCCategoryImpl:
2352 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002353 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002354 case Decl::LinkageSpec:
2355 case Decl::ObjCPropertyImpl:
2356 case Decl::FileScopeAsm:
2357 case Decl::StaticAssert:
2358 case Decl::Block:
2359 return C;
2360
2361 // Declaration kinds that don't make any sense here, but are
2362 // nonetheless harmless.
2363 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002364 break;
2365
2366 // Declaration kinds for which the definition is not resolvable.
2367 case Decl::UnresolvedUsingTypename:
2368 case Decl::UnresolvedUsingValue:
2369 break;
2370
2371 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002372 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2373 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002374
2375 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002376 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002377
2378 case Decl::Enum:
2379 case Decl::Record:
2380 case Decl::CXXRecord:
2381 case Decl::ClassTemplateSpecialization:
2382 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002383 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002384 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002385 return clang_getNullCursor();
2386
2387 case Decl::Function:
2388 case Decl::CXXMethod:
2389 case Decl::CXXConstructor:
2390 case Decl::CXXDestructor:
2391 case Decl::CXXConversion: {
2392 const FunctionDecl *Def = 0;
2393 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002394 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002395 return clang_getNullCursor();
2396 }
2397
2398 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002399 // Ask the variable if it has a definition.
2400 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2401 return MakeCXCursor(Def, CXXUnit);
2402 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002403 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002404
Douglas Gregorb6998662010-01-19 19:34:47 +00002405 case Decl::FunctionTemplate: {
2406 const FunctionDecl *Def = 0;
2407 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002408 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002409 return clang_getNullCursor();
2410 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002411
Douglas Gregorb6998662010-01-19 19:34:47 +00002412 case Decl::ClassTemplate: {
2413 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002414 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002415 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002416 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002417 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002418 return clang_getNullCursor();
2419 }
2420
2421 case Decl::Using: {
2422 UsingDecl *Using = cast<UsingDecl>(D);
2423 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002424 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2425 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002426 S != SEnd; ++S) {
2427 if (Def != clang_getNullCursor()) {
2428 // FIXME: We have no way to return multiple results.
2429 return clang_getNullCursor();
2430 }
2431
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002432 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002433 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002434 }
2435
2436 return Def;
2437 }
2438
2439 case Decl::UsingShadow:
2440 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002441 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002442 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002443
2444 case Decl::ObjCMethod: {
2445 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2446 if (Method->isThisDeclarationADefinition())
2447 return C;
2448
2449 // Dig out the method definition in the associated
2450 // @implementation, if we have it.
2451 // FIXME: The ASTs should make finding the definition easier.
2452 if (ObjCInterfaceDecl *Class
2453 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2454 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2455 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2456 Method->isInstanceMethod()))
2457 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002458 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002459
2460 return clang_getNullCursor();
2461 }
2462
2463 case Decl::ObjCCategory:
2464 if (ObjCCategoryImplDecl *Impl
2465 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002466 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002467 return clang_getNullCursor();
2468
2469 case Decl::ObjCProtocol:
2470 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2471 return C;
2472 return clang_getNullCursor();
2473
2474 case Decl::ObjCInterface:
2475 // There are two notions of a "definition" for an Objective-C
2476 // class: the interface and its implementation. When we resolved a
2477 // reference to an Objective-C class, produce the @interface as
2478 // the definition; when we were provided with the interface,
2479 // produce the @implementation as the definition.
2480 if (WasReference) {
2481 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2482 return C;
2483 } else if (ObjCImplementationDecl *Impl
2484 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002485 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002486 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002487
Douglas Gregorb6998662010-01-19 19:34:47 +00002488 case Decl::ObjCProperty:
2489 // FIXME: We don't really know where to find the
2490 // ObjCPropertyImplDecls that implement this property.
2491 return clang_getNullCursor();
2492
2493 case Decl::ObjCCompatibleAlias:
2494 if (ObjCInterfaceDecl *Class
2495 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2496 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002497 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002498
Douglas Gregorb6998662010-01-19 19:34:47 +00002499 return clang_getNullCursor();
2500
2501 case Decl::ObjCForwardProtocol: {
2502 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2503 if (Forward->protocol_size() == 1)
2504 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002505 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002506 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002507
2508 // FIXME: Cannot return multiple definitions.
2509 return clang_getNullCursor();
2510 }
2511
2512 case Decl::ObjCClass: {
2513 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2514 if (Class->size() == 1) {
2515 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2516 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002517 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002518 return clang_getNullCursor();
2519 }
2520
2521 // FIXME: Cannot return multiple definitions.
2522 return clang_getNullCursor();
2523 }
2524
2525 case Decl::Friend:
2526 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002527 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002528 return clang_getNullCursor();
2529
2530 case Decl::FriendTemplate:
2531 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002532 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002533 return clang_getNullCursor();
2534 }
2535
2536 return clang_getNullCursor();
2537}
2538
2539unsigned clang_isCursorDefinition(CXCursor C) {
2540 if (!clang_isDeclaration(C.kind))
2541 return 0;
2542
2543 return clang_getCursorDefinition(C) == C;
2544}
2545
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002546void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002547 const char **startBuf,
2548 const char **endBuf,
2549 unsigned *startLine,
2550 unsigned *startColumn,
2551 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002552 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002553 assert(getCursorDecl(C) && "CXCursor has null decl");
2554 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002555 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2556 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002557
Steve Naroff4ade6d62009-09-23 17:52:52 +00002558 SourceManager &SM = FD->getASTContext().getSourceManager();
2559 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2560 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2561 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2562 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2563 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2564 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2565}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002566
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002567void clang_enableStackTraces(void) {
2568 llvm::sys::PrintStackTraceOnErrorSignal();
2569}
2570
Ted Kremenekfb480492010-01-13 21:46:36 +00002571} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002572
Ted Kremenekfb480492010-01-13 21:46:36 +00002573//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002574// Token-based Operations.
2575//===----------------------------------------------------------------------===//
2576
2577/* CXToken layout:
2578 * int_data[0]: a CXTokenKind
2579 * int_data[1]: starting token location
2580 * int_data[2]: token length
2581 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002582 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002583 * otherwise unused.
2584 */
2585extern "C" {
2586
2587CXTokenKind clang_getTokenKind(CXToken CXTok) {
2588 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2589}
2590
2591CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2592 switch (clang_getTokenKind(CXTok)) {
2593 case CXToken_Identifier:
2594 case CXToken_Keyword:
2595 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002596 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2597 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002598
2599 case CXToken_Literal: {
2600 // We have stashed the starting pointer in the ptr_data field. Use it.
2601 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002602 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002603 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002604
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002605 case CXToken_Punctuation:
2606 case CXToken_Comment:
2607 break;
2608 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002609
2610 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002611 // deconstructing the source location.
2612 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2613 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002614 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002615
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002616 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2617 std::pair<FileID, unsigned> LocInfo
2618 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002619 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002620 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002621 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2622 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002623 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002624
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002625 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002626}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002627
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002628CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2629 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2630 if (!CXXUnit)
2631 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002632
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002633 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2634 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2635}
2636
2637CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2638 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002639 if (!CXXUnit)
2640 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002641
2642 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002643 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2644}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002645
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002646void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2647 CXToken **Tokens, unsigned *NumTokens) {
2648 if (Tokens)
2649 *Tokens = 0;
2650 if (NumTokens)
2651 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002652
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002653 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2654 if (!CXXUnit || !Tokens || !NumTokens)
2655 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002656
Douglas Gregorbdf60622010-03-05 21:16:25 +00002657 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2658
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002659 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002660 if (R.isInvalid())
2661 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002662
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002663 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2664 std::pair<FileID, unsigned> BeginLocInfo
2665 = SourceMgr.getDecomposedLoc(R.getBegin());
2666 std::pair<FileID, unsigned> EndLocInfo
2667 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002668
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002669 // Cannot tokenize across files.
2670 if (BeginLocInfo.first != EndLocInfo.first)
2671 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002672
2673 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002674 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002675 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002676 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002677 if (Invalid)
2678 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002679
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002680 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2681 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002682 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002683 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002684
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002685 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002686 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002687 llvm::SmallVector<CXToken, 32> CXTokens;
2688 Token Tok;
2689 do {
2690 // Lex the next token
2691 Lex.LexFromRawLexer(Tok);
2692 if (Tok.is(tok::eof))
2693 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002694
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002695 // Initialize the CXToken.
2696 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002697
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002698 // - Common fields
2699 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2700 CXTok.int_data[2] = Tok.getLength();
2701 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002702
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002703 // - Kind-specific fields
2704 if (Tok.isLiteral()) {
2705 CXTok.int_data[0] = CXToken_Literal;
2706 CXTok.ptr_data = (void *)Tok.getLiteralData();
2707 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002708 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002709 std::pair<FileID, unsigned> LocInfo
2710 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002711 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002712 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002713 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2714 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002715 return;
2716
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002717 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002718 IdentifierInfo *II
2719 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002720
2721 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2722 CXTok.int_data[0] = CXToken_Keyword;
2723 }
2724 else {
2725 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2726 CXToken_Identifier
2727 : CXToken_Keyword;
2728 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002729 CXTok.ptr_data = II;
2730 } else if (Tok.is(tok::comment)) {
2731 CXTok.int_data[0] = CXToken_Comment;
2732 CXTok.ptr_data = 0;
2733 } else {
2734 CXTok.int_data[0] = CXToken_Punctuation;
2735 CXTok.ptr_data = 0;
2736 }
2737 CXTokens.push_back(CXTok);
2738 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002739
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002740 if (CXTokens.empty())
2741 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002742
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002743 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2744 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2745 *NumTokens = CXTokens.size();
2746}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002747
Ted Kremenek6db61092010-05-05 00:55:15 +00002748void clang_disposeTokens(CXTranslationUnit TU,
2749 CXToken *Tokens, unsigned NumTokens) {
2750 free(Tokens);
2751}
2752
2753} // end: extern "C"
2754
2755//===----------------------------------------------------------------------===//
2756// Token annotation APIs.
2757//===----------------------------------------------------------------------===//
2758
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002759typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002760static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2761 CXCursor parent,
2762 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002763namespace {
2764class AnnotateTokensWorker {
2765 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002766 CXToken *Tokens;
2767 CXCursor *Cursors;
2768 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002769 unsigned TokIdx;
2770 CursorVisitor AnnotateVis;
2771 SourceManager &SrcMgr;
2772
2773 bool MoreTokens() const { return TokIdx < NumTokens; }
2774 unsigned NextToken() const { return TokIdx; }
2775 void AdvanceToken() { ++TokIdx; }
2776 SourceLocation GetTokenLoc(unsigned tokI) {
2777 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2778 }
2779
Ted Kremenek6db61092010-05-05 00:55:15 +00002780public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002781 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002782 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2783 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002784 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002785 NumTokens(numTokens), TokIdx(0),
2786 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2787 Decl::MaxPCHLevel, RegionOfInterest),
2788 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002789
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002790 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002791 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002792 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002793};
2794}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002795
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002796void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2797 // Walk the AST within the region of interest, annotating tokens
2798 // along the way.
2799 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002800
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002801 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2802 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2803 if (Pos != Annotated.end())
2804 Cursors[I] = Pos->second;
2805 }
2806
2807 // Finish up annotating any tokens left.
2808 if (!MoreTokens())
2809 return;
2810
2811 const CXCursor &C = clang_getNullCursor();
2812 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2813 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2814 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002815 }
2816}
2817
Ted Kremenek6db61092010-05-05 00:55:15 +00002818enum CXChildVisitResult
2819AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002820 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2821 // We can always annotate a preprocessing directive/macro instantiation.
2822 if (clang_isPreprocessing(cursor.kind)) {
2823 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002824 return CXChildVisit_Recurse;
2825 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002826
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002827 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00002828
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002829 if (cursorRange.isInvalid())
2830 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002831
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002832 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2833
Ted Kremeneka333c662010-05-12 05:29:33 +00002834 // Adjust the annotated range based specific declarations.
2835 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2836 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002837 Decl *D = cxcursor::getCursorDecl(cursor);
2838 // Don't visit synthesized ObjC methods, since they have no syntatic
2839 // representation in the source.
2840 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2841 if (MD->isSynthesized())
2842 return CXChildVisit_Continue;
2843 }
2844 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002845 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2846 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002847 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002848 if (TLoc.isValid() &&
2849 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002850 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002851 }
2852 }
2853 }
2854
Ted Kremenek3f404602010-08-14 01:14:06 +00002855 // If the location of the cursor occurs within a macro instantiation, record
2856 // the spelling location of the cursor in our annotation map. We can then
2857 // paper over the token labelings during a post-processing step to try and
2858 // get cursor mappings for tokens that are the *arguments* of a macro
2859 // instantiation.
2860 if (L.isMacroID()) {
2861 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
2862 // Only invalidate the old annotation if it isn't part of a preprocessing
2863 // directive. Here we assume that the default construction of CXCursor
2864 // results in CXCursor.kind being an initialized value (i.e., 0). If
2865 // this isn't the case, we can fix by doing lookup + insertion.
2866
2867 CXCursor &oldC = Annotated[rawEncoding];
2868 if (!clang_isPreprocessing(oldC.kind))
2869 oldC = cursor;
2870 }
2871
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002872 const enum CXCursorKind K = clang_getCursorKind(parent);
2873 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00002874 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
2875 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002876
2877 while (MoreTokens()) {
2878 const unsigned I = NextToken();
2879 SourceLocation TokLoc = GetTokenLoc(I);
2880 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2881 case RangeBefore:
2882 Cursors[I] = updateC;
2883 AdvanceToken();
2884 continue;
2885 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002886 case RangeOverlap:
2887 break;
2888 }
2889 break;
2890 }
2891
2892 // Visit children to get their cursor information.
2893 const unsigned BeforeChildren = NextToken();
2894 VisitChildren(cursor);
2895 const unsigned AfterChildren = NextToken();
2896
2897 // Adjust 'Last' to the last token within the extent of the cursor.
2898 while (MoreTokens()) {
2899 const unsigned I = NextToken();
2900 SourceLocation TokLoc = GetTokenLoc(I);
2901 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2902 case RangeBefore:
2903 assert(0 && "Infeasible");
2904 case RangeAfter:
2905 break;
2906 case RangeOverlap:
2907 Cursors[I] = updateC;
2908 AdvanceToken();
2909 continue;
2910 }
2911 break;
2912 }
2913 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00002914
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002915 // Scan the tokens that are at the beginning of the cursor, but are not
2916 // capture by the child cursors.
2917
2918 // For AST elements within macros, rely on a post-annotate pass to
2919 // to correctly annotate the tokens with cursors. Otherwise we can
2920 // get confusing results of having tokens that map to cursors that really
2921 // are expanded by an instantiation.
2922 if (L.isMacroID())
2923 cursor = clang_getNullCursor();
2924
2925 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2926 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2927 break;
2928 Cursors[I] = cursor;
2929 }
2930 // Scan the tokens that are at the end of the cursor, but are not captured
2931 // but the child cursors.
2932 for (unsigned I = AfterChildren; I != Last; ++I)
2933 Cursors[I] = cursor;
2934
2935 TokIdx = Last;
2936 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002937}
2938
Ted Kremenek6db61092010-05-05 00:55:15 +00002939static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2940 CXCursor parent,
2941 CXClientData client_data) {
2942 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2943}
2944
2945extern "C" {
2946
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002947void clang_annotateTokens(CXTranslationUnit TU,
2948 CXToken *Tokens, unsigned NumTokens,
2949 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002950
2951 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002952 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002953
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002954 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002955 if (!CXXUnit) {
2956 // Any token we don't specifically annotate will have a NULL cursor.
2957 const CXCursor &C = clang_getNullCursor();
2958 for (unsigned I = 0; I != NumTokens; ++I)
2959 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002960 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002961 }
2962
Douglas Gregorbdf60622010-03-05 21:16:25 +00002963 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002964
Douglas Gregor0396f462010-03-19 05:22:59 +00002965 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002966 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002967 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2968 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002969 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
2970 clang_getTokenLocation(TU,
2971 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002972
Douglas Gregor0396f462010-03-19 05:22:59 +00002973 // A mapping from the source locations found when re-lexing or traversing the
2974 // region of interest to the corresponding cursors.
2975 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002976
2977 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00002978 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002979 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2980 std::pair<FileID, unsigned> BeginLocInfo
2981 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2982 std::pair<FileID, unsigned> EndLocInfo
2983 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002984
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002985 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002986 bool Invalid = false;
2987 if (BeginLocInfo.first == EndLocInfo.first &&
2988 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2989 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002990 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2991 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002992 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002993 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002994 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002995
2996 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002997 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002998 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002999 Token Tok;
3000 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003001
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003002 reprocess:
3003 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3004 // We have found a preprocessing directive. Gobble it up so that we
3005 // don't see it while preprocessing these tokens later, but keep track of
3006 // all of the token locations inside this preprocessing directive so that
3007 // we can annotate them appropriately.
3008 //
3009 // FIXME: Some simple tests here could identify macro definitions and
3010 // #undefs, to provide specific cursor kinds for those.
3011 std::vector<SourceLocation> Locations;
3012 do {
3013 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003014 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003015 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003016
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003017 using namespace cxcursor;
3018 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003019 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3020 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003021 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003022 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3023 Annotated[Locations[I].getRawEncoding()] = Cursor;
3024 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003025
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003026 if (Tok.isAtStartOfLine())
3027 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003028
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003029 continue;
3030 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003031
Douglas Gregor48072312010-03-18 15:23:44 +00003032 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003033 break;
3034 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003035 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003036
Douglas Gregor0396f462010-03-19 05:22:59 +00003037 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003038 // a specific cursor.
3039 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3040 CXXUnit, RegionOfInterest);
3041 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003042}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003043} // end: extern "C"
3044
3045//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003046// Operations for querying linkage of a cursor.
3047//===----------------------------------------------------------------------===//
3048
3049extern "C" {
3050CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003051 if (!clang_isDeclaration(cursor.kind))
3052 return CXLinkage_Invalid;
3053
Ted Kremenek16b42592010-03-03 06:36:57 +00003054 Decl *D = cxcursor::getCursorDecl(cursor);
3055 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3056 switch (ND->getLinkage()) {
3057 case NoLinkage: return CXLinkage_NoLinkage;
3058 case InternalLinkage: return CXLinkage_Internal;
3059 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3060 case ExternalLinkage: return CXLinkage_External;
3061 };
3062
3063 return CXLinkage_Invalid;
3064}
3065} // end: extern "C"
3066
3067//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003068// Operations for querying language of a cursor.
3069//===----------------------------------------------------------------------===//
3070
3071static CXLanguageKind getDeclLanguage(const Decl *D) {
3072 switch (D->getKind()) {
3073 default:
3074 break;
3075 case Decl::ImplicitParam:
3076 case Decl::ObjCAtDefsField:
3077 case Decl::ObjCCategory:
3078 case Decl::ObjCCategoryImpl:
3079 case Decl::ObjCClass:
3080 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003081 case Decl::ObjCForwardProtocol:
3082 case Decl::ObjCImplementation:
3083 case Decl::ObjCInterface:
3084 case Decl::ObjCIvar:
3085 case Decl::ObjCMethod:
3086 case Decl::ObjCProperty:
3087 case Decl::ObjCPropertyImpl:
3088 case Decl::ObjCProtocol:
3089 return CXLanguage_ObjC;
3090 case Decl::CXXConstructor:
3091 case Decl::CXXConversion:
3092 case Decl::CXXDestructor:
3093 case Decl::CXXMethod:
3094 case Decl::CXXRecord:
3095 case Decl::ClassTemplate:
3096 case Decl::ClassTemplatePartialSpecialization:
3097 case Decl::ClassTemplateSpecialization:
3098 case Decl::Friend:
3099 case Decl::FriendTemplate:
3100 case Decl::FunctionTemplate:
3101 case Decl::LinkageSpec:
3102 case Decl::Namespace:
3103 case Decl::NamespaceAlias:
3104 case Decl::NonTypeTemplateParm:
3105 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003106 case Decl::TemplateTemplateParm:
3107 case Decl::TemplateTypeParm:
3108 case Decl::UnresolvedUsingTypename:
3109 case Decl::UnresolvedUsingValue:
3110 case Decl::Using:
3111 case Decl::UsingDirective:
3112 case Decl::UsingShadow:
3113 return CXLanguage_CPlusPlus;
3114 }
3115
3116 return CXLanguage_C;
3117}
3118
3119extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003120
3121enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3122 if (clang_isDeclaration(cursor.kind))
3123 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3124 if (D->hasAttr<UnavailableAttr>() ||
3125 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3126 return CXAvailability_Available;
3127
3128 if (D->hasAttr<DeprecatedAttr>())
3129 return CXAvailability_Deprecated;
3130 }
3131
3132 return CXAvailability_Available;
3133}
3134
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003135CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3136 if (clang_isDeclaration(cursor.kind))
3137 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3138
3139 return CXLanguage_Invalid;
3140}
3141} // end: extern "C"
3142
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003143
3144//===----------------------------------------------------------------------===//
3145// C++ AST instrospection.
3146//===----------------------------------------------------------------------===//
3147
3148extern "C" {
3149unsigned clang_CXXMethod_isStatic(CXCursor C) {
3150 if (!clang_isDeclaration(C.kind))
3151 return 0;
3152 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
3153 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003154}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003155
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003156} // end: extern "C"
3157
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003158//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003159// Attribute introspection.
3160//===----------------------------------------------------------------------===//
3161
3162extern "C" {
3163CXType clang_getIBOutletCollectionType(CXCursor C) {
3164 if (C.kind != CXCursor_IBOutletCollectionAttr)
3165 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3166
3167 IBOutletCollectionAttr *A =
3168 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3169
3170 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3171}
3172} // end: extern "C"
3173
3174//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003175// CXString Operations.
3176//===----------------------------------------------------------------------===//
3177
3178extern "C" {
3179const char *clang_getCString(CXString string) {
3180 return string.Spelling;
3181}
3182
3183void clang_disposeString(CXString string) {
3184 if (string.MustFreeString && string.Spelling)
3185 free((void*)string.Spelling);
3186}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003187
Ted Kremenekfb480492010-01-13 21:46:36 +00003188} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003189
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003190namespace clang { namespace cxstring {
3191CXString createCXString(const char *String, bool DupString){
3192 CXString Str;
3193 if (DupString) {
3194 Str.Spelling = strdup(String);
3195 Str.MustFreeString = 1;
3196 } else {
3197 Str.Spelling = String;
3198 Str.MustFreeString = 0;
3199 }
3200 return Str;
3201}
3202
3203CXString createCXString(llvm::StringRef String, bool DupString) {
3204 CXString Result;
3205 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3206 char *Spelling = (char *)malloc(String.size() + 1);
3207 memmove(Spelling, String.data(), String.size());
3208 Spelling[String.size()] = 0;
3209 Result.Spelling = Spelling;
3210 Result.MustFreeString = 1;
3211 } else {
3212 Result.Spelling = String.data();
3213 Result.MustFreeString = 0;
3214 }
3215 return Result;
3216}
3217}}
3218
Ted Kremenek04bb7162010-01-22 22:44:15 +00003219//===----------------------------------------------------------------------===//
3220// Misc. utility functions.
3221//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003222
Ted Kremenek04bb7162010-01-22 22:44:15 +00003223extern "C" {
3224
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003225CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003226 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003227}
3228
3229} // end: extern "C"