blob: 6629f5c0acf0d2075a5f98edfb9bc6e7bf0cb1ca [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);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000293 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 bool VisitEnumConstantDecl(EnumConstantDecl *D);
295 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
296 bool VisitFunctionDecl(FunctionDecl *ND);
297 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000298 bool VisitVarDecl(VarDecl *);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000299 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000300 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
301 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
302 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
303 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000304 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000305 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
306 bool VisitObjCImplDecl(ObjCImplDecl *D);
307 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
308 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
309 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
310 // etc.
311 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
312 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
313 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000314 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000315 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000316
Douglas Gregor01829d32010-08-31 14:41:23 +0000317 // Name visitor
318 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
319
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000320 // Template visitors
321 bool VisitTemplateParameters(const TemplateParameterList *Params);
322 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
323
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000324 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000325 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000326 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000327 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000328 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
329 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000330 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000331 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000332 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000333 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
334 bool VisitPointerTypeLoc(PointerTypeLoc TL);
335 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
336 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
337 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
338 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000339 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000340 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000341 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000342 // FIXME: Implement visitors here when the unimplemented TypeLocs get
343 // implemented
344 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
345 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000346
Douglas Gregora59e3902010-01-21 23:27:09 +0000347 // Statement visitors
348 bool VisitStmt(Stmt *S);
349 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000350 // FIXME: LabelStmt label?
351 bool VisitIfStmt(IfStmt *S);
352 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000353 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000354 bool VisitWhileStmt(WhileStmt *S);
355 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000356// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000357
Douglas Gregor336fd812010-01-23 00:40:08 +0000358 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000359 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
360 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000361 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000362 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000363 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000364 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000365 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000366 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000367 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000368 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000369 // FIXME: AddrLabelExpr (once we have cursors for labels)
370 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
371 bool VisitVAArgExpr(VAArgExpr *E);
372 // FIXME: InitListExpr (for the designators)
373 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000374};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000375
Ted Kremenekab188932010-01-05 19:32:54 +0000376} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000377
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000378static SourceRange getRawCursorExtent(CXCursor C);
379
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000380RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000381 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
382}
383
Douglas Gregorb1373d02010-01-20 20:59:29 +0000384/// \brief Visit the given cursor and, if requested by the visitor,
385/// its children.
386///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000387/// \param Cursor the cursor to visit.
388///
389/// \param CheckRegionOfInterest if true, then the caller already checked that
390/// this cursor is within the region of interest.
391///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000392/// \returns true if the visitation should be aborted, false if it
393/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000394bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395 if (clang_isInvalid(Cursor.kind))
396 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000397
Douglas Gregorb1373d02010-01-20 20:59:29 +0000398 if (clang_isDeclaration(Cursor.kind)) {
399 Decl *D = getCursorDecl(Cursor);
400 assert(D && "Invalid declaration cursor");
401 if (D->getPCHLevel() > MaxPCHLevel)
402 return false;
403
404 if (D->isImplicit())
405 return false;
406 }
407
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000408 // If we have a range of interest, and this cursor doesn't intersect with it,
409 // we're done.
410 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000411 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000412 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000413 return false;
414 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000415
Douglas Gregorb1373d02010-01-20 20:59:29 +0000416 switch (Visitor(Cursor, Parent, ClientData)) {
417 case CXChildVisit_Break:
418 return true;
419
420 case CXChildVisit_Continue:
421 return false;
422
423 case CXChildVisit_Recurse:
424 return VisitChildren(Cursor);
425 }
426
Douglas Gregorfd643772010-01-25 16:45:46 +0000427 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000428}
429
Douglas Gregor788f5a12010-03-20 00:41:21 +0000430std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
431CursorVisitor::getPreprocessedEntities() {
432 PreprocessingRecord &PPRec
433 = *TU->getPreprocessor().getPreprocessingRecord();
434
435 bool OnlyLocalDecls
436 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
437
438 // There is no region of interest; we have to walk everything.
439 if (RegionOfInterest.isInvalid())
440 return std::make_pair(PPRec.begin(OnlyLocalDecls),
441 PPRec.end(OnlyLocalDecls));
442
443 // Find the file in which the region of interest lands.
444 SourceManager &SM = TU->getSourceManager();
445 std::pair<FileID, unsigned> Begin
446 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
447 std::pair<FileID, unsigned> End
448 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
449
450 // The region of interest spans files; we have to walk everything.
451 if (Begin.first != End.first)
452 return std::make_pair(PPRec.begin(OnlyLocalDecls),
453 PPRec.end(OnlyLocalDecls));
454
455 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
456 = TU->getPreprocessedEntitiesByFile();
457 if (ByFileMap.empty()) {
458 // Build the mapping from files to sets of preprocessed entities.
459 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
460 EEnd = PPRec.end(OnlyLocalDecls);
461 E != EEnd; ++E) {
462 std::pair<FileID, unsigned> P
463 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
464 ByFileMap[P.first].push_back(*E);
465 }
466 }
467
468 return std::make_pair(ByFileMap[Begin.first].begin(),
469 ByFileMap[Begin.first].end());
470}
471
Douglas Gregorb1373d02010-01-20 20:59:29 +0000472/// \brief Visit the children of the given cursor.
473///
474/// \returns true if the visitation should be aborted, false if it
475/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000476bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000477 if (clang_isReference(Cursor.kind)) {
478 // By definition, references have no children.
479 return false;
480 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000481
482 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000483 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000484 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000485
Douglas Gregorb1373d02010-01-20 20:59:29 +0000486 if (clang_isDeclaration(Cursor.kind)) {
487 Decl *D = getCursorDecl(Cursor);
488 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000489 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000490 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000491
Douglas Gregora59e3902010-01-21 23:27:09 +0000492 if (clang_isStatement(Cursor.kind))
493 return Visit(getCursorStmt(Cursor));
494 if (clang_isExpression(Cursor.kind))
495 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000496
Douglas Gregorb1373d02010-01-20 20:59:29 +0000497 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000498 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000499 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
500 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000501 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
502 TLEnd = CXXUnit->top_level_end();
503 TL != TLEnd; ++TL) {
504 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000505 return true;
506 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000507 } else if (VisitDeclContext(
508 CXXUnit->getASTContext().getTranslationUnitDecl()))
509 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000510
Douglas Gregor0396f462010-03-19 05:22:59 +0000511 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000512 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000513 // FIXME: Once we have the ability to deserialize a preprocessing record,
514 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000515 PreprocessingRecord::iterator E, EEnd;
516 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000517 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
518 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
519 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000520
Douglas Gregor0396f462010-03-19 05:22:59 +0000521 continue;
522 }
523
524 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
525 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
526 return true;
527
528 continue;
529 }
530 }
531 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000532 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000533 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000534
Douglas Gregorb1373d02010-01-20 20:59:29 +0000535 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000536 return false;
537}
538
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000539bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000540 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
541 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000542
Ted Kremenek664cffd2010-07-22 11:30:19 +0000543 if (Stmt *Body = B->getBody())
544 return Visit(MakeCXCursor(Body, StmtParent, TU));
545
546 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000547}
548
Douglas Gregorb1373d02010-01-20 20:59:29 +0000549bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000550 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000551 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000552
Ted Kremenek23173d72010-05-18 21:09:07 +0000553 Decl *D = *I;
554 if (D->getLexicalDeclContext() != DC)
555 continue;
556
557 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000558
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000559 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000560 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000561 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000562 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000563
564 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000565 case RangeBefore:
566 // This declaration comes before the region of interest; skip it.
567 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000568
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000569 case RangeAfter:
570 // This declaration comes after the region of interest; we're done.
571 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000572
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000573 case RangeOverlap:
574 // This declaration overlaps the region of interest; visit it.
575 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000576 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000577 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000578
Daniel Dunbard52864b2010-02-14 10:02:57 +0000579 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000580 return true;
581 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000582
Douglas Gregorb1373d02010-01-20 20:59:29 +0000583 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000584}
585
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000586bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
587 llvm_unreachable("Translation units are visited directly by Visit()");
588 return false;
589}
590
591bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
592 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
593 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000594
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000595 return false;
596}
597
598bool CursorVisitor::VisitTagDecl(TagDecl *D) {
599 return VisitDeclContext(D);
600}
601
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000602bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
603 // FIXME: Visit default argument
604 return false;
605}
606
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000607bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
608 if (Expr *Init = D->getInitExpr())
609 return Visit(MakeCXCursor(Init, StmtParent, TU));
610 return false;
611}
612
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000613bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
614 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
615 if (Visit(TSInfo->getTypeLoc()))
616 return true;
617
618 return false;
619}
620
Douglas Gregorb1373d02010-01-20 20:59:29 +0000621bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000622 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
623 // Visit the function declaration's syntactic components in the order
624 // written. This requires a bit of work.
625 TypeLoc TL = TSInfo->getTypeLoc();
626 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
627
628 // If we have a function declared directly (without the use of a typedef),
629 // visit just the return type. Otherwise, just visit the function's type
630 // now.
631 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
632 (!FTL && Visit(TL)))
633 return true;
634
635 // FIXME: Visit the nested-name-specifier, if present.
636
637 // Visit the declaration name.
638 if (VisitDeclarationNameInfo(ND->getNameInfo()))
639 return true;
640
641 // FIXME: Visit explicitly-specified template arguments!
642
643 // Visit the function parameters, if we have a function type.
644 if (FTL && VisitFunctionTypeLoc(*FTL, true))
645 return true;
646
647 // FIXME: Attributes?
648 }
649
Douglas Gregora59e3902010-01-21 23:27:09 +0000650 if (ND->isThisDeclarationADefinition() &&
651 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
652 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000653
Douglas Gregorb1373d02010-01-20 20:59:29 +0000654 return false;
655}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000656
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000657bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
658 if (VisitDeclaratorDecl(D))
659 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000660
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000661 if (Expr *BitWidth = D->getBitWidth())
662 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000663
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000664 return false;
665}
666
667bool CursorVisitor::VisitVarDecl(VarDecl *D) {
668 if (VisitDeclaratorDecl(D))
669 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000670
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000671 if (Expr *Init = D->getInit())
672 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000673
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000674 return false;
675}
676
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000677bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
678 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
679 // before visiting these template parameters.
680 if (VisitTemplateParameters(D->getTemplateParameters()))
681 return true;
682
683 return VisitFunctionDecl(D->getTemplatedDecl());
684}
685
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000686bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000687 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
688 if (Visit(TSInfo->getTypeLoc()))
689 return true;
690
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000691 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000692 PEnd = ND->param_end();
693 P != PEnd; ++P) {
694 if (Visit(MakeCXCursor(*P, TU)))
695 return true;
696 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000697
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000698 if (ND->isThisDeclarationADefinition() &&
699 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
700 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000701
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000702 return false;
703}
704
Douglas Gregora59e3902010-01-21 23:27:09 +0000705bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
706 return VisitDeclContext(D);
707}
708
Douglas Gregorb1373d02010-01-20 20:59:29 +0000709bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000710 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
711 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000712 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000713
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000714 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
715 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
716 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000717 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000718 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000719
Douglas Gregora59e3902010-01-21 23:27:09 +0000720 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000721}
722
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000723bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
724 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
725 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
726 E = PID->protocol_end(); I != E; ++I, ++PL)
727 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
728 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000729
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000730 return VisitObjCContainerDecl(PID);
731}
732
Ted Kremenek23173d72010-05-18 21:09:07 +0000733bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000734 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
735 return true;
736
Ted Kremenek23173d72010-05-18 21:09:07 +0000737 // FIXME: This implements a workaround with @property declarations also being
738 // installed in the DeclContext for the @interface. Eventually this code
739 // should be removed.
740 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
741 if (!CDecl || !CDecl->IsClassExtension())
742 return false;
743
744 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
745 if (!ID)
746 return false;
747
748 IdentifierInfo *PropertyId = PD->getIdentifier();
749 ObjCPropertyDecl *prevDecl =
750 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
751
752 if (!prevDecl)
753 return false;
754
755 // Visit synthesized methods since they will be skipped when visiting
756 // the @interface.
757 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
758 if (MD->isSynthesized())
759 if (Visit(MakeCXCursor(MD, TU)))
760 return true;
761
762 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
763 if (MD->isSynthesized())
764 if (Visit(MakeCXCursor(MD, TU)))
765 return true;
766
767 return false;
768}
769
Douglas Gregorb1373d02010-01-20 20:59:29 +0000770bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000771 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000772 if (D->getSuperClass() &&
773 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000774 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000775 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000776 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000777
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000778 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
779 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
780 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000781 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000782 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783
Douglas Gregora59e3902010-01-21 23:27:09 +0000784 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000785}
786
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000787bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
788 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000789}
790
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000791bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000792 // 'ID' could be null when dealing with invalid code.
793 if (ObjCInterfaceDecl *ID = D->getClassInterface())
794 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
795 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797 return VisitObjCImplDecl(D);
798}
799
800bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
801#if 0
802 // Issue callbacks for super class.
803 // FIXME: No source location information!
804 if (D->getSuperClass() &&
805 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000806 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000807 TU)))
808 return true;
809#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000810
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000811 return VisitObjCImplDecl(D);
812}
813
814bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
815 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
816 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
817 E = D->protocol_end();
818 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000819 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000820 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000821
822 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000823}
824
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000825bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
826 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
827 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
828 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000829
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000830 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000831}
832
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000833bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
834 return VisitDeclContext(D);
835}
836
Douglas Gregor01829d32010-08-31 14:41:23 +0000837bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
838 switch (Name.getName().getNameKind()) {
839 case clang::DeclarationName::Identifier:
840 case clang::DeclarationName::CXXLiteralOperatorName:
841 case clang::DeclarationName::CXXOperatorName:
842 case clang::DeclarationName::CXXUsingDirective:
843 return false;
844
845 case clang::DeclarationName::CXXConstructorName:
846 case clang::DeclarationName::CXXDestructorName:
847 case clang::DeclarationName::CXXConversionFunctionName:
848 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
849 return Visit(TSInfo->getTypeLoc());
850 return false;
851
852 case clang::DeclarationName::ObjCZeroArgSelector:
853 case clang::DeclarationName::ObjCOneArgSelector:
854 case clang::DeclarationName::ObjCMultiArgSelector:
855 // FIXME: Per-identifier location info?
856 return false;
857 }
858
859 return false;
860}
861
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000862bool CursorVisitor::VisitTemplateParameters(
863 const TemplateParameterList *Params) {
864 if (!Params)
865 return false;
866
867 for (TemplateParameterList::const_iterator P = Params->begin(),
868 PEnd = Params->end();
869 P != PEnd; ++P) {
870 if (Visit(MakeCXCursor(*P, TU)))
871 return true;
872 }
873
874 return false;
875}
876
877bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
878 switch (TAL.getArgument().getKind()) {
879 case TemplateArgument::Null:
880 case TemplateArgument::Integral:
881 return false;
882
883 case TemplateArgument::Pack:
884 // FIXME: Implement when variadic templates come along.
885 return false;
886
887 case TemplateArgument::Type:
888 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
889 return Visit(TSInfo->getTypeLoc());
890 return false;
891
892 case TemplateArgument::Declaration:
893 if (Expr *E = TAL.getSourceDeclExpression())
894 return Visit(MakeCXCursor(E, StmtParent, TU));
895 return false;
896
897 case TemplateArgument::Expression:
898 if (Expr *E = TAL.getSourceExpression())
899 return Visit(MakeCXCursor(E, StmtParent, TU));
900 return false;
901
902 case TemplateArgument::Template:
903 // FIXME: Visit template name.
904 return false;
905 }
906
907 return false;
908}
909
Ted Kremeneka0536d82010-05-07 01:04:29 +0000910bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
911 return VisitDeclContext(D);
912}
913
Douglas Gregor01829d32010-08-31 14:41:23 +0000914bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
915 return Visit(TL.getUnqualifiedLoc());
916}
917
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000918bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
919 ASTContext &Context = TU->getASTContext();
920
921 // Some builtin types (such as Objective-C's "id", "sel", and
922 // "Class") have associated declarations. Create cursors for those.
923 QualType VisitType;
924 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000925 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000926 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000927 case BuiltinType::Char_U:
928 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000929 case BuiltinType::Char16:
930 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000931 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000932 case BuiltinType::UInt:
933 case BuiltinType::ULong:
934 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000935 case BuiltinType::UInt128:
936 case BuiltinType::Char_S:
937 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000938 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000939 case BuiltinType::Short:
940 case BuiltinType::Int:
941 case BuiltinType::Long:
942 case BuiltinType::LongLong:
943 case BuiltinType::Int128:
944 case BuiltinType::Float:
945 case BuiltinType::Double:
946 case BuiltinType::LongDouble:
947 case BuiltinType::NullPtr:
948 case BuiltinType::Overload:
949 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000950 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000951
952 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000953 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000954
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000955 case BuiltinType::ObjCId:
956 VisitType = Context.getObjCIdType();
957 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000958
959 case BuiltinType::ObjCClass:
960 VisitType = Context.getObjCClassType();
961 break;
962
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000963 case BuiltinType::ObjCSel:
964 VisitType = Context.getObjCSelType();
965 break;
966 }
967
968 if (!VisitType.isNull()) {
969 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000970 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000971 TU));
972 }
973
974 return false;
975}
976
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000977bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
978 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
979}
980
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000981bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
982 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
983}
984
985bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
986 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
987}
988
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000989bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
990 // FIXME: We can't visit the template template parameter, but there's
991 // no context information with which we can match up the depth/index in the
992 // type to the appropriate
993 return false;
994}
995
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000996bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
997 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
998 return true;
999
John McCallc12c5bb2010-05-15 11:32:37 +00001000 return false;
1001}
1002
1003bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1004 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1005 return true;
1006
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001007 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1008 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1009 TU)))
1010 return true;
1011 }
1012
1013 return false;
1014}
1015
1016bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001017 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001018}
1019
1020bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1021 return Visit(TL.getPointeeLoc());
1022}
1023
1024bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1025 return Visit(TL.getPointeeLoc());
1026}
1027
1028bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1029 return Visit(TL.getPointeeLoc());
1030}
1031
1032bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001033 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001034}
1035
1036bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001037 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001038}
1039
Douglas Gregor01829d32010-08-31 14:41:23 +00001040bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1041 bool SkipResultType) {
1042 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001043 return true;
1044
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001045 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001046 if (Decl *D = TL.getArg(I))
1047 if (Visit(MakeCXCursor(D, TU)))
1048 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001049
1050 return false;
1051}
1052
1053bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1054 if (Visit(TL.getElementLoc()))
1055 return true;
1056
1057 if (Expr *Size = TL.getSizeExpr())
1058 return Visit(MakeCXCursor(Size, StmtParent, TU));
1059
1060 return false;
1061}
1062
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001063bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1064 TemplateSpecializationTypeLoc TL) {
1065 // FIXME: Visit the template name.
1066
1067 // Visit the template arguments.
1068 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1069 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1070 return true;
1071
1072 return false;
1073}
1074
Douglas Gregor2332c112010-01-21 20:48:56 +00001075bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1076 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1077}
1078
1079bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1080 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1081 return Visit(TSInfo->getTypeLoc());
1082
1083 return false;
1084}
1085
Douglas Gregora59e3902010-01-21 23:27:09 +00001086bool CursorVisitor::VisitStmt(Stmt *S) {
1087 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1088 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001089 if (Stmt *C = *Child)
1090 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1091 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001092 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001093
Douglas Gregora59e3902010-01-21 23:27:09 +00001094 return false;
1095}
1096
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001097bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1098 // Specially handle CaseStmts because they can be nested, e.g.:
1099 //
1100 // case 1:
1101 // case 2:
1102 //
1103 // In this case the second CaseStmt is the child of the first. Walking
1104 // these recursively can blow out the stack.
1105 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1106 while (true) {
1107 // Set the Parent field to Cursor, then back to its old value once we're
1108 // done.
1109 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1110
1111 if (Stmt *LHS = S->getLHS())
1112 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1113 return true;
1114 if (Stmt *RHS = S->getRHS())
1115 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1116 return true;
1117 if (Stmt *SubStmt = S->getSubStmt()) {
1118 if (!isa<CaseStmt>(SubStmt))
1119 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1120
1121 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1122 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1123 Cursor = MakeCXCursor(CS, StmtParent, TU);
1124 if (RegionOfInterest.isValid()) {
1125 SourceRange Range = CS->getSourceRange();
1126 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1127 return false;
1128 }
1129
1130 switch (Visitor(Cursor, Parent, ClientData)) {
1131 case CXChildVisit_Break: return true;
1132 case CXChildVisit_Continue: return false;
1133 case CXChildVisit_Recurse:
1134 // Perform tail-recursion manually.
1135 S = CS;
1136 continue;
1137 }
1138 }
1139 return false;
1140 }
1141}
1142
Douglas Gregora59e3902010-01-21 23:27:09 +00001143bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1144 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1145 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001146 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001147 return true;
1148 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001149
Douglas Gregora59e3902010-01-21 23:27:09 +00001150 return false;
1151}
1152
Douglas Gregorf5bab412010-01-22 01:00:11 +00001153bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1154 if (VarDecl *Var = S->getConditionVariable()) {
1155 if (Visit(MakeCXCursor(Var, TU)))
1156 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001157 }
1158
Douglas Gregor263b47b2010-01-25 16:12:32 +00001159 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1160 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001161 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1162 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001163 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1164 return true;
1165
1166 return false;
1167}
1168
1169bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1170 if (VarDecl *Var = S->getConditionVariable()) {
1171 if (Visit(MakeCXCursor(Var, TU)))
1172 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001173 }
1174
Douglas Gregor263b47b2010-01-25 16:12:32 +00001175 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1176 return true;
1177 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1178 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001179
Douglas Gregor263b47b2010-01-25 16:12:32 +00001180 return false;
1181}
1182
1183bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1184 if (VarDecl *Var = S->getConditionVariable()) {
1185 if (Visit(MakeCXCursor(Var, TU)))
1186 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001187 }
1188
Douglas Gregor263b47b2010-01-25 16:12:32 +00001189 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1190 return true;
1191 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001192 return true;
1193
Douglas Gregor263b47b2010-01-25 16:12:32 +00001194 return false;
1195}
1196
1197bool CursorVisitor::VisitForStmt(ForStmt *S) {
1198 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1199 return true;
1200 if (VarDecl *Var = S->getConditionVariable()) {
1201 if (Visit(MakeCXCursor(Var, TU)))
1202 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001203 }
1204
Douglas Gregor263b47b2010-01-25 16:12:32 +00001205 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1206 return true;
1207 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1208 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001209 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1210 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001211
Douglas Gregorf5bab412010-01-22 01:00:11 +00001212 return false;
1213}
1214
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001215bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1216 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1217 return true;
1218
1219 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1220 return true;
1221
1222 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1223 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1224 return true;
1225
1226 return false;
1227}
1228
Ted Kremenek3064ef92010-08-27 21:34:58 +00001229bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1230 if (D->isDefinition()) {
1231 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1232 E = D->bases_end(); I != E; ++I) {
1233 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1234 return true;
1235 }
1236 }
1237
1238 return VisitTagDecl(D);
1239}
1240
1241
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001242bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1243 return Visit(B->getBlockDecl());
1244}
1245
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001246bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1247 // FIXME: Visit fields as well?
1248 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1249 return true;
1250
1251 return VisitExpr(E);
1252}
1253
Douglas Gregor336fd812010-01-23 00:40:08 +00001254bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1255 if (E->isArgumentType()) {
1256 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1257 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001258
Douglas Gregor336fd812010-01-23 00:40:08 +00001259 return false;
1260 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001261
Douglas Gregor336fd812010-01-23 00:40:08 +00001262 return VisitExpr(E);
1263}
1264
1265bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1266 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1267 if (Visit(TSInfo->getTypeLoc()))
1268 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001269
Douglas Gregor336fd812010-01-23 00:40:08 +00001270 return VisitCastExpr(E);
1271}
1272
1273bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1274 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1275 if (Visit(TSInfo->getTypeLoc()))
1276 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001277
Douglas Gregor336fd812010-01-23 00:40:08 +00001278 return VisitExpr(E);
1279}
1280
Douglas Gregor648220e2010-08-10 15:02:34 +00001281bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1282 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1283 Visit(E->getArgTInfo2()->getTypeLoc());
1284}
1285
1286bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1287 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1288 return true;
1289
1290 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1291}
1292
Douglas Gregorc2350e52010-03-08 16:40:19 +00001293bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001294 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1295 if (Visit(TSInfo->getTypeLoc()))
1296 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001297
1298 return VisitExpr(E);
1299}
1300
Douglas Gregor81d34662010-04-20 15:39:42 +00001301bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1302 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1303}
1304
1305
Ted Kremenek09dfa372010-02-18 05:46:33 +00001306bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001307 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1308 i != e; ++i)
1309 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001310 return true;
1311
1312 return false;
1313}
1314
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001315extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001316CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1317 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001318 // We use crash recovery to make some of our APIs more reliable, implicitly
1319 // enable it.
1320 llvm::CrashRecoveryContext::Enable();
1321
Douglas Gregora030b7c2010-01-22 20:35:53 +00001322 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001323 if (excludeDeclarationsFromPCH)
1324 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001325 if (displayDiagnostics)
1326 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001327 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001328}
1329
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001330void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001331 if (CIdx)
1332 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001333 if (getenv("LIBCLANG_TIMING"))
1334 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001335}
1336
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001337void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001338 if (CIdx) {
1339 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1340 CXXIdx->setUseExternalASTGeneration(value);
1341 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001342}
1343
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001344CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001345 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001346 if (!CIdx)
1347 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001348
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001349 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001350
Douglas Gregor28019772010-04-05 23:52:57 +00001351 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001352 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001353 CXXIdx->getOnlyLocalDecls(),
1354 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001355}
1356
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001357unsigned clang_defaultEditingTranslationUnitOptions() {
1358 return CXTranslationUnit_PrecompiledPreamble;
1359}
1360
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001361CXTranslationUnit
1362clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1363 const char *source_filename,
1364 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001365 const char **command_line_args,
1366 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001367 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001368 return clang_parseTranslationUnit(CIdx, source_filename,
1369 command_line_args, num_command_line_args,
1370 unsaved_files, num_unsaved_files,
1371 CXTranslationUnit_DetailedPreprocessingRecord);
1372}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001373
1374struct ParseTranslationUnitInfo {
1375 CXIndex CIdx;
1376 const char *source_filename;
1377 const char **command_line_args;
1378 int num_command_line_args;
1379 struct CXUnsavedFile *unsaved_files;
1380 unsigned num_unsaved_files;
1381 unsigned options;
1382 CXTranslationUnit result;
1383};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001384static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001385 ParseTranslationUnitInfo *PTUI =
1386 static_cast<ParseTranslationUnitInfo*>(UserData);
1387 CXIndex CIdx = PTUI->CIdx;
1388 const char *source_filename = PTUI->source_filename;
1389 const char **command_line_args = PTUI->command_line_args;
1390 int num_command_line_args = PTUI->num_command_line_args;
1391 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1392 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1393 unsigned options = PTUI->options;
1394 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001395
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001396 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001397 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001398
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001399 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1400
Douglas Gregor44c181a2010-07-23 00:33:23 +00001401 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001402 bool CompleteTranslationUnit
1403 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001404 bool CacheCodeCompetionResults
1405 = options & CXTranslationUnit_CacheCompletionResults;
1406
Douglas Gregor5352ac02010-01-28 00:27:43 +00001407 // Configure the diagnostics.
1408 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001409 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1410 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001411
Douglas Gregor4db64a42010-01-23 00:14:00 +00001412 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1413 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001414 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001415 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001416 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001417 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1418 Buffer));
1419 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001420
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001421 if (!CXXIdx->getUseExternalASTGeneration()) {
1422 llvm::SmallVector<const char *, 16> Args;
1423
1424 // The 'source_filename' argument is optional. If the caller does not
1425 // specify it then it is assumed that the source file is specified
1426 // in the actual argument list.
1427 if (source_filename)
1428 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001429
1430 // Since the Clang C library is primarily used by batch tools dealing with
1431 // (often very broken) source code, where spell-checking can have a
1432 // significant negative impact on performance (particularly when
1433 // precompiled headers are involved), we disable it by default.
1434 // Note that we place this argument early in the list, so that it can be
1435 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001436 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001437
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001438 Args.insert(Args.end(), command_line_args,
1439 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001440
Douglas Gregor44c181a2010-07-23 00:33:23 +00001441 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001442 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1443 Args.push_back("-Xclang");
1444 Args.push_back("-detailed-preprocessing-record");
1445 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001446
Douglas Gregor5352ac02010-01-28 00:27:43 +00001447 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001448
Ted Kremenek29b72842010-01-07 22:49:05 +00001449#ifdef USE_CRASHTRACER
1450 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001451#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001452
Daniel Dunbar94220972009-12-05 02:17:18 +00001453 llvm::OwningPtr<ASTUnit> Unit(
1454 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001455 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001456 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001457 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001458 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001459 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001460 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001461 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001462 CompleteTranslationUnit,
1463 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001464
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001465 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001466 // Make sure to check that 'Unit' is non-NULL.
1467 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001468 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1469 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001470 D != DEnd; ++D) {
1471 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001472 CXString Msg = clang_formatDiagnostic(&Diag,
1473 clang_defaultDiagnosticDisplayOptions());
1474 fprintf(stderr, "%s\n", clang_getCString(Msg));
1475 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001476 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001477#ifdef LLVM_ON_WIN32
1478 // On Windows, force a flush, since there may be multiple copies of
1479 // stderr and stdout in the file system, all with different buffers
1480 // but writing to the same device.
1481 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001482#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001483 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001484 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001485
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001486 PTUI->result = Unit.take();
1487 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001488 }
1489
Ted Kremenek139ba862009-10-22 00:03:57 +00001490 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001491 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001492
Ted Kremenek139ba862009-10-22 00:03:57 +00001493 // First add the complete path to the 'clang' executable.
1494 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001495 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001496
Ted Kremenek139ba862009-10-22 00:03:57 +00001497 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001498 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001499
Ted Kremenek139ba862009-10-22 00:03:57 +00001500 // The 'source_filename' argument is optional. If the caller does not
1501 // specify it then it is assumed that the source file is specified
1502 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001503 if (source_filename)
1504 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001505
Steve Naroff37b5ac22009-10-15 20:50:09 +00001506 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001507 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001508 char astTmpFile[L_tmpnam];
1509 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001510
1511 // Since the Clang C library is primarily used by batch tools dealing with
1512 // (often very broken) source code, where spell-checking can have a
1513 // significant negative impact on performance (particularly when
1514 // precompiled headers are involved), we disable it by default.
1515 // Note that we place this argument early in the list, so that it can be
1516 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001517 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001518
Douglas Gregor4db64a42010-01-23 00:14:00 +00001519 // Remap any unsaved files to temporary files.
1520 std::vector<llvm::sys::Path> TemporaryFiles;
1521 std::vector<std::string> RemapArgs;
1522 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001523 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001524
Douglas Gregor4db64a42010-01-23 00:14:00 +00001525 // The pointers into the elements of RemapArgs are stable because we
1526 // won't be adding anything to RemapArgs after this point.
1527 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1528 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001529
Ted Kremenek139ba862009-10-22 00:03:57 +00001530 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1531 for (int i = 0; i < num_command_line_args; ++i)
1532 if (const char *arg = command_line_args[i]) {
1533 if (strcmp(arg, "-o") == 0) {
1534 ++i; // Also skip the matching argument.
1535 continue;
1536 }
1537 if (strcmp(arg, "-emit-ast") == 0 ||
1538 strcmp(arg, "-c") == 0 ||
1539 strcmp(arg, "-fsyntax-only") == 0) {
1540 continue;
1541 }
1542
1543 // Keep the argument.
1544 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001545 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001546
Douglas Gregord93256e2010-01-28 06:00:51 +00001547 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001548 char tmpFileResults[L_tmpnam];
1549 char *tmpResultsFileName = tmpnam(tmpFileResults);
1550 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001551 TemporaryFiles.push_back(DiagnosticsFile);
1552 argv.push_back("-fdiagnostics-binary");
1553
Douglas Gregor44c181a2010-07-23 00:33:23 +00001554 // Do we need the detailed preprocessing record?
1555 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1556 argv.push_back("-Xclang");
1557 argv.push_back("-detailed-preprocessing-record");
1558 }
1559
Ted Kremenek139ba862009-10-22 00:03:57 +00001560 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001561 argv.push_back(NULL);
1562
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001563 // Invoke 'clang'.
1564 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1565 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001566 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001567 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1568 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001569 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001570 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001571 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001572
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001573 if (!ErrMsg.empty()) {
1574 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001575 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001576 I != E; ++I) {
1577 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001578 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001579 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001580 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001581
Daniel Dunbar32141c82010-02-23 20:23:45 +00001582 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001583 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001584
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001585 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001586 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001587 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001588 RemappedFiles.size(),
1589 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001590 if (ATU) {
1591 LoadSerializedDiagnostics(DiagnosticsFile,
1592 num_unsaved_files, unsaved_files,
1593 ATU->getFileManager(),
1594 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001595 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001596 } else if (CXXIdx->getDisplayDiagnostics()) {
1597 // We failed to load the ASTUnit, but we can still deserialize the
1598 // diagnostics and emit them.
1599 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001600 Diagnostic Diag;
1601 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001602 // FIXME: Faked LangOpts!
1603 LangOptions LangOpts;
1604 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1605 LoadSerializedDiagnostics(DiagnosticsFile,
1606 num_unsaved_files, unsaved_files,
1607 FileMgr, SourceMgr, Diags);
1608 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1609 DEnd = Diags.end();
1610 D != DEnd; ++D) {
1611 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001612 CXString Msg = clang_formatDiagnostic(&Diag,
1613 clang_defaultDiagnosticDisplayOptions());
1614 fprintf(stderr, "%s\n", clang_getCString(Msg));
1615 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001616 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001617
1618#ifdef LLVM_ON_WIN32
1619 // On Windows, force a flush, since there may be multiple copies of
1620 // stderr and stdout in the file system, all with different buffers
1621 // but writing to the same device.
1622 fflush(stderr);
1623#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001624 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001625
Douglas Gregor313e26c2010-02-18 23:35:40 +00001626 if (ATU) {
1627 // Make the translation unit responsible for destroying all temporary files.
1628 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1629 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001630 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001631 } else {
1632 // Destroy all of the temporary files now; they can't be referenced any
1633 // longer.
1634 llvm::sys::Path(astTmpFile).eraseFromDisk();
1635 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1636 TemporaryFiles[i].eraseFromDisk();
1637 }
1638
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001639 PTUI->result = ATU;
1640}
1641CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1642 const char *source_filename,
1643 const char **command_line_args,
1644 int num_command_line_args,
1645 struct CXUnsavedFile *unsaved_files,
1646 unsigned num_unsaved_files,
1647 unsigned options) {
1648 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1649 num_command_line_args, unsaved_files, num_unsaved_files,
1650 options, 0 };
1651 llvm::CrashRecoveryContext CRC;
1652
1653 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001654 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1655 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1656 fprintf(stderr, " 'command_line_args' : [");
1657 for (int i = 0; i != num_command_line_args; ++i) {
1658 if (i)
1659 fprintf(stderr, ", ");
1660 fprintf(stderr, "'%s'", command_line_args[i]);
1661 }
1662 fprintf(stderr, "],\n");
1663 fprintf(stderr, " 'unsaved_files' : [");
1664 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1665 if (i)
1666 fprintf(stderr, ", ");
1667 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1668 unsaved_files[i].Length);
1669 }
1670 fprintf(stderr, "],\n");
1671 fprintf(stderr, " 'options' : %d,\n", options);
1672 fprintf(stderr, "}\n");
1673
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001674 return 0;
1675 }
1676
1677 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001678}
1679
Douglas Gregor19998442010-08-13 15:35:05 +00001680unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1681 return CXSaveTranslationUnit_None;
1682}
1683
1684int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1685 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001686 if (!TU)
1687 return 1;
1688
1689 return static_cast<ASTUnit *>(TU)->Save(FileName);
1690}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001691
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001692void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001693 if (CTUnit) {
1694 // If the translation unit has been marked as unsafe to free, just discard
1695 // it.
1696 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1697 return;
1698
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001699 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001700 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001701}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001702
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001703unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1704 return CXReparse_None;
1705}
1706
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001707struct ReparseTranslationUnitInfo {
1708 CXTranslationUnit TU;
1709 unsigned num_unsaved_files;
1710 struct CXUnsavedFile *unsaved_files;
1711 unsigned options;
1712 int result;
1713};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001714static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001715 ReparseTranslationUnitInfo *RTUI =
1716 static_cast<ReparseTranslationUnitInfo*>(UserData);
1717 CXTranslationUnit TU = RTUI->TU;
1718 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1719 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1720 unsigned options = RTUI->options;
1721 (void) options;
1722 RTUI->result = 1;
1723
Douglas Gregorabc563f2010-07-19 21:46:24 +00001724 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001725 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001726
1727 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1728 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1729 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1730 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001731 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001732 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1733 Buffer));
1734 }
1735
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001736 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1737 RemappedFiles.size()))
1738 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001739}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001740int clang_reparseTranslationUnit(CXTranslationUnit TU,
1741 unsigned num_unsaved_files,
1742 struct CXUnsavedFile *unsaved_files,
1743 unsigned options) {
1744 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1745 options, 0 };
1746 llvm::CrashRecoveryContext CRC;
1747
1748 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001749 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001750 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1751 return 1;
1752 }
1753
1754 return RTUI.result;
1755}
1756
Douglas Gregordf95a132010-08-09 20:45:32 +00001757
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001758CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001759 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001760 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001761
Steve Naroff77accc12009-09-03 18:19:54 +00001762 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001763 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001764}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001765
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001766CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001767 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001768 return Result;
1769}
1770
Ted Kremenekfb480492010-01-13 21:46:36 +00001771} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001772
Ted Kremenekfb480492010-01-13 21:46:36 +00001773//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001774// CXSourceLocation and CXSourceRange Operations.
1775//===----------------------------------------------------------------------===//
1776
Douglas Gregorb9790342010-01-22 21:44:22 +00001777extern "C" {
1778CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001779 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001780 return Result;
1781}
1782
1783unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001784 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1785 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1786 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001787}
1788
1789CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1790 CXFile file,
1791 unsigned line,
1792 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001793 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001794 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001795
Douglas Gregorb9790342010-01-22 21:44:22 +00001796 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1797 SourceLocation SLoc
1798 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001799 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001800 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001801
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001802 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001803}
1804
Douglas Gregor5352ac02010-01-28 00:27:43 +00001805CXSourceRange clang_getNullRange() {
1806 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1807 return Result;
1808}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001809
Douglas Gregor5352ac02010-01-28 00:27:43 +00001810CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1811 if (begin.ptr_data[0] != end.ptr_data[0] ||
1812 begin.ptr_data[1] != end.ptr_data[1])
1813 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001814
1815 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001816 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001817 return Result;
1818}
1819
Douglas Gregor46766dc2010-01-26 19:19:08 +00001820void clang_getInstantiationLocation(CXSourceLocation location,
1821 CXFile *file,
1822 unsigned *line,
1823 unsigned *column,
1824 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001825 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1826
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001827 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001828 if (file)
1829 *file = 0;
1830 if (line)
1831 *line = 0;
1832 if (column)
1833 *column = 0;
1834 if (offset)
1835 *offset = 0;
1836 return;
1837 }
1838
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001839 const SourceManager &SM =
1840 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001841 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001842
1843 if (file)
1844 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1845 if (line)
1846 *line = SM.getInstantiationLineNumber(InstLoc);
1847 if (column)
1848 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001849 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001850 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001851}
1852
Douglas Gregor1db19de2010-01-19 21:36:55 +00001853CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001854 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001855 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001856 return Result;
1857}
1858
1859CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001860 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001861 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001862 return Result;
1863}
1864
Douglas Gregorb9790342010-01-22 21:44:22 +00001865} // end: extern "C"
1866
Douglas Gregor1db19de2010-01-19 21:36:55 +00001867//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001868// CXFile Operations.
1869//===----------------------------------------------------------------------===//
1870
1871extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001872CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001873 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001874 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001875
Steve Naroff88145032009-10-27 14:35:18 +00001876 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001877 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001878}
1879
1880time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001881 if (!SFile)
1882 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001883
Steve Naroff88145032009-10-27 14:35:18 +00001884 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1885 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001886}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001887
Douglas Gregorb9790342010-01-22 21:44:22 +00001888CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1889 if (!tu)
1890 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001891
Douglas Gregorb9790342010-01-22 21:44:22 +00001892 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001893
Douglas Gregorb9790342010-01-22 21:44:22 +00001894 FileManager &FMgr = CXXUnit->getFileManager();
1895 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1896 return const_cast<FileEntry *>(File);
1897}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001898
Ted Kremenekfb480492010-01-13 21:46:36 +00001899} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001900
Ted Kremenekfb480492010-01-13 21:46:36 +00001901//===----------------------------------------------------------------------===//
1902// CXCursor Operations.
1903//===----------------------------------------------------------------------===//
1904
Ted Kremenekfb480492010-01-13 21:46:36 +00001905static Decl *getDeclFromExpr(Stmt *E) {
1906 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1907 return RefExpr->getDecl();
1908 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1909 return ME->getMemberDecl();
1910 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1911 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001912
Ted Kremenekfb480492010-01-13 21:46:36 +00001913 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1914 return getDeclFromExpr(CE->getCallee());
1915 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1916 return getDeclFromExpr(CE->getSubExpr());
1917 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1918 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001919
Ted Kremenekfb480492010-01-13 21:46:36 +00001920 return 0;
1921}
1922
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001923static SourceLocation getLocationFromExpr(Expr *E) {
1924 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1925 return /*FIXME:*/Msg->getLeftLoc();
1926 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1927 return DRE->getLocation();
1928 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1929 return Member->getMemberLoc();
1930 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1931 return Ivar->getLocation();
1932 return E->getLocStart();
1933}
1934
Ted Kremenekfb480492010-01-13 21:46:36 +00001935extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001936
1937unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001938 CXCursorVisitor visitor,
1939 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001940 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001941
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001942 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1943 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00001944 return CursorVis.VisitChildren(parent);
1945}
1946
Douglas Gregor78205d42010-01-20 21:45:58 +00001947static CXString getDeclSpelling(Decl *D) {
1948 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1949 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001950 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001951
Douglas Gregor78205d42010-01-20 21:45:58 +00001952 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001953 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001954
Douglas Gregor78205d42010-01-20 21:45:58 +00001955 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1956 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1957 // and returns different names. NamedDecl returns the class name and
1958 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001959 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001960
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001961 llvm::SmallString<1024> S;
1962 llvm::raw_svector_ostream os(S);
1963 ND->printName(os);
1964
1965 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001966}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001967
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001968CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001969 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001970 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001971
Steve Narofff334b4e2009-09-02 18:26:48 +00001972 if (clang_isReference(C.kind)) {
1973 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001974 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001975 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001976 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001977 }
1978 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001979 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001980 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001981 }
1982 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001983 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001984 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001985 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001986 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00001987 case CXCursor_CXXBaseSpecifier: {
1988 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
1989 return createCXString(B->getType().getAsString());
1990 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001991 case CXCursor_TypeRef: {
1992 TypeDecl *Type = getCursorTypeRef(C).first;
1993 assert(Type && "Missing type decl");
1994
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001995 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1996 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001997 }
1998
Daniel Dunbaracca7252009-11-30 20:42:49 +00001999 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002000 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002001 }
2002 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002003
2004 if (clang_isExpression(C.kind)) {
2005 Decl *D = getDeclFromExpr(getCursorExpr(C));
2006 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002007 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002008 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002009 }
2010
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002011 if (C.kind == CXCursor_MacroInstantiation)
2012 return createCXString(getCursorMacroInstantiation(C)->getName()
2013 ->getNameStart());
2014
Douglas Gregor572feb22010-03-18 18:04:21 +00002015 if (C.kind == CXCursor_MacroDefinition)
2016 return createCXString(getCursorMacroDefinition(C)->getName()
2017 ->getNameStart());
2018
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002019 if (clang_isDeclaration(C.kind))
2020 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002021
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002022 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002023}
2024
Ted Kremeneke68fff62010-02-17 00:41:32 +00002025CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002026 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002027 case CXCursor_FunctionDecl:
2028 return createCXString("FunctionDecl");
2029 case CXCursor_TypedefDecl:
2030 return createCXString("TypedefDecl");
2031 case CXCursor_EnumDecl:
2032 return createCXString("EnumDecl");
2033 case CXCursor_EnumConstantDecl:
2034 return createCXString("EnumConstantDecl");
2035 case CXCursor_StructDecl:
2036 return createCXString("StructDecl");
2037 case CXCursor_UnionDecl:
2038 return createCXString("UnionDecl");
2039 case CXCursor_ClassDecl:
2040 return createCXString("ClassDecl");
2041 case CXCursor_FieldDecl:
2042 return createCXString("FieldDecl");
2043 case CXCursor_VarDecl:
2044 return createCXString("VarDecl");
2045 case CXCursor_ParmDecl:
2046 return createCXString("ParmDecl");
2047 case CXCursor_ObjCInterfaceDecl:
2048 return createCXString("ObjCInterfaceDecl");
2049 case CXCursor_ObjCCategoryDecl:
2050 return createCXString("ObjCCategoryDecl");
2051 case CXCursor_ObjCProtocolDecl:
2052 return createCXString("ObjCProtocolDecl");
2053 case CXCursor_ObjCPropertyDecl:
2054 return createCXString("ObjCPropertyDecl");
2055 case CXCursor_ObjCIvarDecl:
2056 return createCXString("ObjCIvarDecl");
2057 case CXCursor_ObjCInstanceMethodDecl:
2058 return createCXString("ObjCInstanceMethodDecl");
2059 case CXCursor_ObjCClassMethodDecl:
2060 return createCXString("ObjCClassMethodDecl");
2061 case CXCursor_ObjCImplementationDecl:
2062 return createCXString("ObjCImplementationDecl");
2063 case CXCursor_ObjCCategoryImplDecl:
2064 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002065 case CXCursor_CXXMethod:
2066 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002067 case CXCursor_UnexposedDecl:
2068 return createCXString("UnexposedDecl");
2069 case CXCursor_ObjCSuperClassRef:
2070 return createCXString("ObjCSuperClassRef");
2071 case CXCursor_ObjCProtocolRef:
2072 return createCXString("ObjCProtocolRef");
2073 case CXCursor_ObjCClassRef:
2074 return createCXString("ObjCClassRef");
2075 case CXCursor_TypeRef:
2076 return createCXString("TypeRef");
2077 case CXCursor_UnexposedExpr:
2078 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002079 case CXCursor_BlockExpr:
2080 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002081 case CXCursor_DeclRefExpr:
2082 return createCXString("DeclRefExpr");
2083 case CXCursor_MemberRefExpr:
2084 return createCXString("MemberRefExpr");
2085 case CXCursor_CallExpr:
2086 return createCXString("CallExpr");
2087 case CXCursor_ObjCMessageExpr:
2088 return createCXString("ObjCMessageExpr");
2089 case CXCursor_UnexposedStmt:
2090 return createCXString("UnexposedStmt");
2091 case CXCursor_InvalidFile:
2092 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002093 case CXCursor_InvalidCode:
2094 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002095 case CXCursor_NoDeclFound:
2096 return createCXString("NoDeclFound");
2097 case CXCursor_NotImplemented:
2098 return createCXString("NotImplemented");
2099 case CXCursor_TranslationUnit:
2100 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002101 case CXCursor_UnexposedAttr:
2102 return createCXString("UnexposedAttr");
2103 case CXCursor_IBActionAttr:
2104 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002105 case CXCursor_IBOutletAttr:
2106 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002107 case CXCursor_IBOutletCollectionAttr:
2108 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002109 case CXCursor_PreprocessingDirective:
2110 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002111 case CXCursor_MacroDefinition:
2112 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002113 case CXCursor_MacroInstantiation:
2114 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002115 case CXCursor_Namespace:
2116 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002117 case CXCursor_LinkageSpec:
2118 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002119 case CXCursor_CXXBaseSpecifier:
2120 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002121 case CXCursor_Constructor:
2122 return createCXString("CXXConstructor");
2123 case CXCursor_Destructor:
2124 return createCXString("CXXDestructor");
2125 case CXCursor_ConversionFunction:
2126 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002127 case CXCursor_TemplateTypeParameter:
2128 return createCXString("TemplateTypeParameter");
2129 case CXCursor_NonTypeTemplateParameter:
2130 return createCXString("NonTypeTemplateParameter");
2131 case CXCursor_TemplateTemplateParameter:
2132 return createCXString("TemplateTemplateParameter");
2133 case CXCursor_FunctionTemplate:
2134 return createCXString("FunctionTemplate");
Steve Naroff89922f82009-08-31 00:59:03 +00002135 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002136
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002137 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002138 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002139}
Steve Naroff89922f82009-08-31 00:59:03 +00002140
Ted Kremeneke68fff62010-02-17 00:41:32 +00002141enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2142 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002143 CXClientData client_data) {
2144 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2145 *BestCursor = cursor;
2146 return CXChildVisit_Recurse;
2147}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002148
Douglas Gregorb9790342010-01-22 21:44:22 +00002149CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2150 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002151 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002152
Douglas Gregorb9790342010-01-22 21:44:22 +00002153 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002154 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2155
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002156 // Translate the given source location to make it point at the beginning of
2157 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002158 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002159
2160 // Guard against an invalid SourceLocation, or we may assert in one
2161 // of the following calls.
2162 if (SLoc.isInvalid())
2163 return clang_getNullCursor();
2164
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002165 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2166 CXXUnit->getASTContext().getLangOptions());
2167
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002168 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2169 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002170 // FIXME: Would be great to have a "hint" cursor, then walk from that
2171 // hint cursor upward until we find a cursor whose source range encloses
2172 // the region of interest, rather than starting from the translation unit.
2173 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002174 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002175 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002176 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002177 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002178 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002179}
2180
Ted Kremenek73885552009-11-17 19:28:59 +00002181CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002182 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002183}
2184
2185unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002186 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002187}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002188
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002189unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002190 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2191}
2192
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002193unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002194 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2195}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002196
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002197unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002198 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2199}
2200
Douglas Gregor97b98722010-01-19 23:20:36 +00002201unsigned clang_isExpression(enum CXCursorKind K) {
2202 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2203}
2204
2205unsigned clang_isStatement(enum CXCursorKind K) {
2206 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2207}
2208
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002209unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2210 return K == CXCursor_TranslationUnit;
2211}
2212
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002213unsigned clang_isPreprocessing(enum CXCursorKind K) {
2214 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2215}
2216
Ted Kremenekad6eff62010-03-08 21:17:29 +00002217unsigned clang_isUnexposed(enum CXCursorKind K) {
2218 switch (K) {
2219 case CXCursor_UnexposedDecl:
2220 case CXCursor_UnexposedExpr:
2221 case CXCursor_UnexposedStmt:
2222 case CXCursor_UnexposedAttr:
2223 return true;
2224 default:
2225 return false;
2226 }
2227}
2228
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002229CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002230 return C.kind;
2231}
2232
Douglas Gregor98258af2010-01-18 22:46:11 +00002233CXSourceLocation clang_getCursorLocation(CXCursor C) {
2234 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002235 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002236 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002237 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2238 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002239 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002240 }
2241
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002242 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002243 std::pair<ObjCProtocolDecl *, SourceLocation> P
2244 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002245 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002246 }
2247
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002248 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002249 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2250 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002251 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002252 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002253
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002254 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002255 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002256 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002257 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002258
2259 case CXCursor_CXXBaseSpecifier: {
2260 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2261 return clang_getNullLocation();
2262 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002263
Douglas Gregorf46034a2010-01-18 23:41:10 +00002264 default:
2265 // FIXME: Need a way to enumerate all non-reference cases.
2266 llvm_unreachable("Missed a reference kind");
2267 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002268 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002269
2270 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002271 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002272 getLocationFromExpr(getCursorExpr(C)));
2273
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002274 if (C.kind == CXCursor_PreprocessingDirective) {
2275 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2276 return cxloc::translateSourceLocation(getCursorContext(C), L);
2277 }
Douglas Gregor48072312010-03-18 15:23:44 +00002278
2279 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002280 SourceLocation L
2281 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002282 return cxloc::translateSourceLocation(getCursorContext(C), L);
2283 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002284
2285 if (C.kind == CXCursor_MacroDefinition) {
2286 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2287 return cxloc::translateSourceLocation(getCursorContext(C), L);
2288 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002289
Ted Kremenek9a700d22010-05-12 06:16:13 +00002290 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002291 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002292
Douglas Gregorf46034a2010-01-18 23:41:10 +00002293 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002294 SourceLocation Loc = D->getLocation();
2295 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2296 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002297 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002298}
Douglas Gregora7bde202010-01-19 00:34:46 +00002299
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002300} // end extern "C"
2301
2302static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002303 if (clang_isReference(C.kind)) {
2304 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002305 case CXCursor_ObjCSuperClassRef:
2306 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002307
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002308 case CXCursor_ObjCProtocolRef:
2309 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002310
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002311 case CXCursor_ObjCClassRef:
2312 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002313
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002314 case CXCursor_TypeRef:
2315 return getCursorTypeRef(C).second;
Ted Kremenek3064ef92010-08-27 21:34:58 +00002316
2317 case CXCursor_CXXBaseSpecifier:
2318 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2319 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002320
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002321 default:
2322 // FIXME: Need a way to enumerate all non-reference cases.
2323 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002324 }
2325 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002326
2327 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002328 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002329
2330 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002331 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002332
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002333 if (C.kind == CXCursor_PreprocessingDirective)
2334 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002335
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002336 if (C.kind == CXCursor_MacroInstantiation)
2337 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002338
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002339 if (C.kind == CXCursor_MacroDefinition)
2340 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002341
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002342 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2343 return getCursorDecl(C)->getSourceRange();
2344
2345 return SourceRange();
2346}
2347
2348extern "C" {
2349
2350CXSourceRange clang_getCursorExtent(CXCursor C) {
2351 SourceRange R = getRawCursorExtent(C);
2352 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002353 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002354
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002355 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002356}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002357
2358CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002359 if (clang_isInvalid(C.kind))
2360 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002361
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002362 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002363 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002364 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002365
Douglas Gregor97b98722010-01-19 23:20:36 +00002366 if (clang_isExpression(C.kind)) {
2367 Decl *D = getDeclFromExpr(getCursorExpr(C));
2368 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002369 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002370 return clang_getNullCursor();
2371 }
2372
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002373 if (C.kind == CXCursor_MacroInstantiation) {
2374 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2375 return MakeMacroDefinitionCursor(Def, CXXUnit);
2376 }
2377
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002378 if (!clang_isReference(C.kind))
2379 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002380
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002381 switch (C.kind) {
2382 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002383 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002384
2385 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002386 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002387
2388 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002389 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002390
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002391 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002392 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenek3064ef92010-08-27 21:34:58 +00002393
2394 case CXCursor_CXXBaseSpecifier: {
2395 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2396 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2397 CXXUnit));
2398 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002399
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002400 default:
2401 // We would prefer to enumerate all non-reference cursor kinds here.
2402 llvm_unreachable("Unhandled reference cursor kind");
2403 break;
2404 }
2405 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002406
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002407 return clang_getNullCursor();
2408}
2409
Douglas Gregorb6998662010-01-19 19:34:47 +00002410CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002411 if (clang_isInvalid(C.kind))
2412 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002413
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002414 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002415
Douglas Gregorb6998662010-01-19 19:34:47 +00002416 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002417 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002418 C = clang_getCursorReferenced(C);
2419 WasReference = true;
2420 }
2421
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002422 if (C.kind == CXCursor_MacroInstantiation)
2423 return clang_getCursorReferenced(C);
2424
Douglas Gregorb6998662010-01-19 19:34:47 +00002425 if (!clang_isDeclaration(C.kind))
2426 return clang_getNullCursor();
2427
2428 Decl *D = getCursorDecl(C);
2429 if (!D)
2430 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002431
Douglas Gregorb6998662010-01-19 19:34:47 +00002432 switch (D->getKind()) {
2433 // Declaration kinds that don't really separate the notions of
2434 // declaration and definition.
2435 case Decl::Namespace:
2436 case Decl::Typedef:
2437 case Decl::TemplateTypeParm:
2438 case Decl::EnumConstant:
2439 case Decl::Field:
2440 case Decl::ObjCIvar:
2441 case Decl::ObjCAtDefsField:
2442 case Decl::ImplicitParam:
2443 case Decl::ParmVar:
2444 case Decl::NonTypeTemplateParm:
2445 case Decl::TemplateTemplateParm:
2446 case Decl::ObjCCategoryImpl:
2447 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002448 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002449 case Decl::LinkageSpec:
2450 case Decl::ObjCPropertyImpl:
2451 case Decl::FileScopeAsm:
2452 case Decl::StaticAssert:
2453 case Decl::Block:
2454 return C;
2455
2456 // Declaration kinds that don't make any sense here, but are
2457 // nonetheless harmless.
2458 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002459 break;
2460
2461 // Declaration kinds for which the definition is not resolvable.
2462 case Decl::UnresolvedUsingTypename:
2463 case Decl::UnresolvedUsingValue:
2464 break;
2465
2466 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002467 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2468 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002469
2470 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002471 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002472
2473 case Decl::Enum:
2474 case Decl::Record:
2475 case Decl::CXXRecord:
2476 case Decl::ClassTemplateSpecialization:
2477 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002478 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002479 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002480 return clang_getNullCursor();
2481
2482 case Decl::Function:
2483 case Decl::CXXMethod:
2484 case Decl::CXXConstructor:
2485 case Decl::CXXDestructor:
2486 case Decl::CXXConversion: {
2487 const FunctionDecl *Def = 0;
2488 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002489 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002490 return clang_getNullCursor();
2491 }
2492
2493 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002494 // Ask the variable if it has a definition.
2495 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2496 return MakeCXCursor(Def, CXXUnit);
2497 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002498 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002499
Douglas Gregorb6998662010-01-19 19:34:47 +00002500 case Decl::FunctionTemplate: {
2501 const FunctionDecl *Def = 0;
2502 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002503 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002504 return clang_getNullCursor();
2505 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002506
Douglas Gregorb6998662010-01-19 19:34:47 +00002507 case Decl::ClassTemplate: {
2508 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002509 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002510 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002511 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002512 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002513 return clang_getNullCursor();
2514 }
2515
2516 case Decl::Using: {
2517 UsingDecl *Using = cast<UsingDecl>(D);
2518 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002519 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2520 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002521 S != SEnd; ++S) {
2522 if (Def != clang_getNullCursor()) {
2523 // FIXME: We have no way to return multiple results.
2524 return clang_getNullCursor();
2525 }
2526
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002527 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002528 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002529 }
2530
2531 return Def;
2532 }
2533
2534 case Decl::UsingShadow:
2535 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002536 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002537 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002538
2539 case Decl::ObjCMethod: {
2540 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2541 if (Method->isThisDeclarationADefinition())
2542 return C;
2543
2544 // Dig out the method definition in the associated
2545 // @implementation, if we have it.
2546 // FIXME: The ASTs should make finding the definition easier.
2547 if (ObjCInterfaceDecl *Class
2548 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2549 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2550 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2551 Method->isInstanceMethod()))
2552 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002553 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002554
2555 return clang_getNullCursor();
2556 }
2557
2558 case Decl::ObjCCategory:
2559 if (ObjCCategoryImplDecl *Impl
2560 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002561 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002562 return clang_getNullCursor();
2563
2564 case Decl::ObjCProtocol:
2565 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2566 return C;
2567 return clang_getNullCursor();
2568
2569 case Decl::ObjCInterface:
2570 // There are two notions of a "definition" for an Objective-C
2571 // class: the interface and its implementation. When we resolved a
2572 // reference to an Objective-C class, produce the @interface as
2573 // the definition; when we were provided with the interface,
2574 // produce the @implementation as the definition.
2575 if (WasReference) {
2576 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2577 return C;
2578 } else if (ObjCImplementationDecl *Impl
2579 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002580 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002581 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002582
Douglas Gregorb6998662010-01-19 19:34:47 +00002583 case Decl::ObjCProperty:
2584 // FIXME: We don't really know where to find the
2585 // ObjCPropertyImplDecls that implement this property.
2586 return clang_getNullCursor();
2587
2588 case Decl::ObjCCompatibleAlias:
2589 if (ObjCInterfaceDecl *Class
2590 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2591 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002592 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002593
Douglas Gregorb6998662010-01-19 19:34:47 +00002594 return clang_getNullCursor();
2595
2596 case Decl::ObjCForwardProtocol: {
2597 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2598 if (Forward->protocol_size() == 1)
2599 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002600 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002601 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002602
2603 // FIXME: Cannot return multiple definitions.
2604 return clang_getNullCursor();
2605 }
2606
2607 case Decl::ObjCClass: {
2608 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2609 if (Class->size() == 1) {
2610 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2611 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002612 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002613 return clang_getNullCursor();
2614 }
2615
2616 // FIXME: Cannot return multiple definitions.
2617 return clang_getNullCursor();
2618 }
2619
2620 case Decl::Friend:
2621 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002622 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002623 return clang_getNullCursor();
2624
2625 case Decl::FriendTemplate:
2626 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002627 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002628 return clang_getNullCursor();
2629 }
2630
2631 return clang_getNullCursor();
2632}
2633
2634unsigned clang_isCursorDefinition(CXCursor C) {
2635 if (!clang_isDeclaration(C.kind))
2636 return 0;
2637
2638 return clang_getCursorDefinition(C) == C;
2639}
2640
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002641void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002642 const char **startBuf,
2643 const char **endBuf,
2644 unsigned *startLine,
2645 unsigned *startColumn,
2646 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002647 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002648 assert(getCursorDecl(C) && "CXCursor has null decl");
2649 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002650 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2651 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002652
Steve Naroff4ade6d62009-09-23 17:52:52 +00002653 SourceManager &SM = FD->getASTContext().getSourceManager();
2654 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2655 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2656 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2657 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2658 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2659 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2660}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002661
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002662void clang_enableStackTraces(void) {
2663 llvm::sys::PrintStackTraceOnErrorSignal();
2664}
2665
Ted Kremenekfb480492010-01-13 21:46:36 +00002666} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002667
Ted Kremenekfb480492010-01-13 21:46:36 +00002668//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002669// Token-based Operations.
2670//===----------------------------------------------------------------------===//
2671
2672/* CXToken layout:
2673 * int_data[0]: a CXTokenKind
2674 * int_data[1]: starting token location
2675 * int_data[2]: token length
2676 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002677 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002678 * otherwise unused.
2679 */
2680extern "C" {
2681
2682CXTokenKind clang_getTokenKind(CXToken CXTok) {
2683 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2684}
2685
2686CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2687 switch (clang_getTokenKind(CXTok)) {
2688 case CXToken_Identifier:
2689 case CXToken_Keyword:
2690 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002691 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2692 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002693
2694 case CXToken_Literal: {
2695 // We have stashed the starting pointer in the ptr_data field. Use it.
2696 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002697 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002698 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002699
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002700 case CXToken_Punctuation:
2701 case CXToken_Comment:
2702 break;
2703 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002704
2705 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002706 // deconstructing the source location.
2707 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2708 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002709 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002710
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002711 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2712 std::pair<FileID, unsigned> LocInfo
2713 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002714 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002715 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002716 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2717 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002718 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002719
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002720 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002721}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002722
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002723CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2724 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2725 if (!CXXUnit)
2726 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002727
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002728 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2729 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2730}
2731
2732CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2733 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002734 if (!CXXUnit)
2735 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002736
2737 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002738 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2739}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002740
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002741void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2742 CXToken **Tokens, unsigned *NumTokens) {
2743 if (Tokens)
2744 *Tokens = 0;
2745 if (NumTokens)
2746 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002747
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002748 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2749 if (!CXXUnit || !Tokens || !NumTokens)
2750 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002751
Douglas Gregorbdf60622010-03-05 21:16:25 +00002752 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2753
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002754 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002755 if (R.isInvalid())
2756 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002757
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002758 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2759 std::pair<FileID, unsigned> BeginLocInfo
2760 = SourceMgr.getDecomposedLoc(R.getBegin());
2761 std::pair<FileID, unsigned> EndLocInfo
2762 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002763
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002764 // Cannot tokenize across files.
2765 if (BeginLocInfo.first != EndLocInfo.first)
2766 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002767
2768 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002769 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002770 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002771 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002772 if (Invalid)
2773 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002774
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002775 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2776 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002777 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002778 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002779
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002780 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002781 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002782 llvm::SmallVector<CXToken, 32> CXTokens;
2783 Token Tok;
2784 do {
2785 // Lex the next token
2786 Lex.LexFromRawLexer(Tok);
2787 if (Tok.is(tok::eof))
2788 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002789
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002790 // Initialize the CXToken.
2791 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002792
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002793 // - Common fields
2794 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2795 CXTok.int_data[2] = Tok.getLength();
2796 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002797
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002798 // - Kind-specific fields
2799 if (Tok.isLiteral()) {
2800 CXTok.int_data[0] = CXToken_Literal;
2801 CXTok.ptr_data = (void *)Tok.getLiteralData();
2802 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002803 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002804 std::pair<FileID, unsigned> LocInfo
2805 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002806 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002807 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002808 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2809 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002810 return;
2811
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002812 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002813 IdentifierInfo *II
2814 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002815
2816 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2817 CXTok.int_data[0] = CXToken_Keyword;
2818 }
2819 else {
2820 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2821 CXToken_Identifier
2822 : CXToken_Keyword;
2823 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002824 CXTok.ptr_data = II;
2825 } else if (Tok.is(tok::comment)) {
2826 CXTok.int_data[0] = CXToken_Comment;
2827 CXTok.ptr_data = 0;
2828 } else {
2829 CXTok.int_data[0] = CXToken_Punctuation;
2830 CXTok.ptr_data = 0;
2831 }
2832 CXTokens.push_back(CXTok);
2833 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002834
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002835 if (CXTokens.empty())
2836 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002837
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002838 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2839 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2840 *NumTokens = CXTokens.size();
2841}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002842
Ted Kremenek6db61092010-05-05 00:55:15 +00002843void clang_disposeTokens(CXTranslationUnit TU,
2844 CXToken *Tokens, unsigned NumTokens) {
2845 free(Tokens);
2846}
2847
2848} // end: extern "C"
2849
2850//===----------------------------------------------------------------------===//
2851// Token annotation APIs.
2852//===----------------------------------------------------------------------===//
2853
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002854typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002855static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2856 CXCursor parent,
2857 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002858namespace {
2859class AnnotateTokensWorker {
2860 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002861 CXToken *Tokens;
2862 CXCursor *Cursors;
2863 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002864 unsigned TokIdx;
2865 CursorVisitor AnnotateVis;
2866 SourceManager &SrcMgr;
2867
2868 bool MoreTokens() const { return TokIdx < NumTokens; }
2869 unsigned NextToken() const { return TokIdx; }
2870 void AdvanceToken() { ++TokIdx; }
2871 SourceLocation GetTokenLoc(unsigned tokI) {
2872 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2873 }
2874
Ted Kremenek6db61092010-05-05 00:55:15 +00002875public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002876 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002877 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2878 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002879 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002880 NumTokens(numTokens), TokIdx(0),
2881 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2882 Decl::MaxPCHLevel, RegionOfInterest),
2883 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002884
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002885 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002886 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002887 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002888};
2889}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002890
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002891void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2892 // Walk the AST within the region of interest, annotating tokens
2893 // along the way.
2894 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002895
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002896 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2897 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2898 if (Pos != Annotated.end())
2899 Cursors[I] = Pos->second;
2900 }
2901
2902 // Finish up annotating any tokens left.
2903 if (!MoreTokens())
2904 return;
2905
2906 const CXCursor &C = clang_getNullCursor();
2907 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2908 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2909 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002910 }
2911}
2912
Ted Kremenek6db61092010-05-05 00:55:15 +00002913enum CXChildVisitResult
2914AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002915 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2916 // We can always annotate a preprocessing directive/macro instantiation.
2917 if (clang_isPreprocessing(cursor.kind)) {
2918 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002919 return CXChildVisit_Recurse;
2920 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002921
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002922 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00002923
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002924 if (cursorRange.isInvalid())
2925 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002926
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002927 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2928
Ted Kremeneka333c662010-05-12 05:29:33 +00002929 // Adjust the annotated range based specific declarations.
2930 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2931 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002932 Decl *D = cxcursor::getCursorDecl(cursor);
2933 // Don't visit synthesized ObjC methods, since they have no syntatic
2934 // representation in the source.
2935 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2936 if (MD->isSynthesized())
2937 return CXChildVisit_Continue;
2938 }
2939 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002940 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2941 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002942 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002943 if (TLoc.isValid() &&
2944 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002945 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002946 }
2947 }
2948 }
2949
Ted Kremenek3f404602010-08-14 01:14:06 +00002950 // If the location of the cursor occurs within a macro instantiation, record
2951 // the spelling location of the cursor in our annotation map. We can then
2952 // paper over the token labelings during a post-processing step to try and
2953 // get cursor mappings for tokens that are the *arguments* of a macro
2954 // instantiation.
2955 if (L.isMacroID()) {
2956 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
2957 // Only invalidate the old annotation if it isn't part of a preprocessing
2958 // directive. Here we assume that the default construction of CXCursor
2959 // results in CXCursor.kind being an initialized value (i.e., 0). If
2960 // this isn't the case, we can fix by doing lookup + insertion.
2961
2962 CXCursor &oldC = Annotated[rawEncoding];
2963 if (!clang_isPreprocessing(oldC.kind))
2964 oldC = cursor;
2965 }
2966
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002967 const enum CXCursorKind K = clang_getCursorKind(parent);
2968 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00002969 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
2970 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002971
2972 while (MoreTokens()) {
2973 const unsigned I = NextToken();
2974 SourceLocation TokLoc = GetTokenLoc(I);
2975 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2976 case RangeBefore:
2977 Cursors[I] = updateC;
2978 AdvanceToken();
2979 continue;
2980 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002981 case RangeOverlap:
2982 break;
2983 }
2984 break;
2985 }
2986
2987 // Visit children to get their cursor information.
2988 const unsigned BeforeChildren = NextToken();
2989 VisitChildren(cursor);
2990 const unsigned AfterChildren = NextToken();
2991
2992 // Adjust 'Last' to the last token within the extent of the cursor.
2993 while (MoreTokens()) {
2994 const unsigned I = NextToken();
2995 SourceLocation TokLoc = GetTokenLoc(I);
2996 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2997 case RangeBefore:
2998 assert(0 && "Infeasible");
2999 case RangeAfter:
3000 break;
3001 case RangeOverlap:
3002 Cursors[I] = updateC;
3003 AdvanceToken();
3004 continue;
3005 }
3006 break;
3007 }
3008 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003009
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003010 // Scan the tokens that are at the beginning of the cursor, but are not
3011 // capture by the child cursors.
3012
3013 // For AST elements within macros, rely on a post-annotate pass to
3014 // to correctly annotate the tokens with cursors. Otherwise we can
3015 // get confusing results of having tokens that map to cursors that really
3016 // are expanded by an instantiation.
3017 if (L.isMacroID())
3018 cursor = clang_getNullCursor();
3019
3020 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3021 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3022 break;
3023 Cursors[I] = cursor;
3024 }
3025 // Scan the tokens that are at the end of the cursor, but are not captured
3026 // but the child cursors.
3027 for (unsigned I = AfterChildren; I != Last; ++I)
3028 Cursors[I] = cursor;
3029
3030 TokIdx = Last;
3031 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003032}
3033
Ted Kremenek6db61092010-05-05 00:55:15 +00003034static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3035 CXCursor parent,
3036 CXClientData client_data) {
3037 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3038}
3039
3040extern "C" {
3041
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003042void clang_annotateTokens(CXTranslationUnit TU,
3043 CXToken *Tokens, unsigned NumTokens,
3044 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003045
3046 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003047 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003048
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003049 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003050 if (!CXXUnit) {
3051 // Any token we don't specifically annotate will have a NULL cursor.
3052 const CXCursor &C = clang_getNullCursor();
3053 for (unsigned I = 0; I != NumTokens; ++I)
3054 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003055 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003056 }
3057
Douglas Gregorbdf60622010-03-05 21:16:25 +00003058 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003059
Douglas Gregor0396f462010-03-19 05:22:59 +00003060 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003061 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003062 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3063 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003064 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3065 clang_getTokenLocation(TU,
3066 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003067
Douglas Gregor0396f462010-03-19 05:22:59 +00003068 // A mapping from the source locations found when re-lexing or traversing the
3069 // region of interest to the corresponding cursors.
3070 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003071
3072 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003073 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003074 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3075 std::pair<FileID, unsigned> BeginLocInfo
3076 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3077 std::pair<FileID, unsigned> EndLocInfo
3078 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003079
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003080 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003081 bool Invalid = false;
3082 if (BeginLocInfo.first == EndLocInfo.first &&
3083 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3084 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003085 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3086 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003087 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003088 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003089 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003090
3091 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003092 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003093 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003094 Token Tok;
3095 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003096
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003097 reprocess:
3098 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3099 // We have found a preprocessing directive. Gobble it up so that we
3100 // don't see it while preprocessing these tokens later, but keep track of
3101 // all of the token locations inside this preprocessing directive so that
3102 // we can annotate them appropriately.
3103 //
3104 // FIXME: Some simple tests here could identify macro definitions and
3105 // #undefs, to provide specific cursor kinds for those.
3106 std::vector<SourceLocation> Locations;
3107 do {
3108 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003109 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003110 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003111
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003112 using namespace cxcursor;
3113 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003114 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3115 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003116 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003117 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3118 Annotated[Locations[I].getRawEncoding()] = Cursor;
3119 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003120
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003121 if (Tok.isAtStartOfLine())
3122 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003123
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003124 continue;
3125 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003126
Douglas Gregor48072312010-03-18 15:23:44 +00003127 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003128 break;
3129 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003130 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003131
Douglas Gregor0396f462010-03-19 05:22:59 +00003132 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003133 // a specific cursor.
3134 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3135 CXXUnit, RegionOfInterest);
3136 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003137}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003138} // end: extern "C"
3139
3140//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003141// Operations for querying linkage of a cursor.
3142//===----------------------------------------------------------------------===//
3143
3144extern "C" {
3145CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003146 if (!clang_isDeclaration(cursor.kind))
3147 return CXLinkage_Invalid;
3148
Ted Kremenek16b42592010-03-03 06:36:57 +00003149 Decl *D = cxcursor::getCursorDecl(cursor);
3150 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3151 switch (ND->getLinkage()) {
3152 case NoLinkage: return CXLinkage_NoLinkage;
3153 case InternalLinkage: return CXLinkage_Internal;
3154 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3155 case ExternalLinkage: return CXLinkage_External;
3156 };
3157
3158 return CXLinkage_Invalid;
3159}
3160} // end: extern "C"
3161
3162//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003163// Operations for querying language of a cursor.
3164//===----------------------------------------------------------------------===//
3165
3166static CXLanguageKind getDeclLanguage(const Decl *D) {
3167 switch (D->getKind()) {
3168 default:
3169 break;
3170 case Decl::ImplicitParam:
3171 case Decl::ObjCAtDefsField:
3172 case Decl::ObjCCategory:
3173 case Decl::ObjCCategoryImpl:
3174 case Decl::ObjCClass:
3175 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003176 case Decl::ObjCForwardProtocol:
3177 case Decl::ObjCImplementation:
3178 case Decl::ObjCInterface:
3179 case Decl::ObjCIvar:
3180 case Decl::ObjCMethod:
3181 case Decl::ObjCProperty:
3182 case Decl::ObjCPropertyImpl:
3183 case Decl::ObjCProtocol:
3184 return CXLanguage_ObjC;
3185 case Decl::CXXConstructor:
3186 case Decl::CXXConversion:
3187 case Decl::CXXDestructor:
3188 case Decl::CXXMethod:
3189 case Decl::CXXRecord:
3190 case Decl::ClassTemplate:
3191 case Decl::ClassTemplatePartialSpecialization:
3192 case Decl::ClassTemplateSpecialization:
3193 case Decl::Friend:
3194 case Decl::FriendTemplate:
3195 case Decl::FunctionTemplate:
3196 case Decl::LinkageSpec:
3197 case Decl::Namespace:
3198 case Decl::NamespaceAlias:
3199 case Decl::NonTypeTemplateParm:
3200 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003201 case Decl::TemplateTemplateParm:
3202 case Decl::TemplateTypeParm:
3203 case Decl::UnresolvedUsingTypename:
3204 case Decl::UnresolvedUsingValue:
3205 case Decl::Using:
3206 case Decl::UsingDirective:
3207 case Decl::UsingShadow:
3208 return CXLanguage_CPlusPlus;
3209 }
3210
3211 return CXLanguage_C;
3212}
3213
3214extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003215
3216enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3217 if (clang_isDeclaration(cursor.kind))
3218 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3219 if (D->hasAttr<UnavailableAttr>() ||
3220 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3221 return CXAvailability_Available;
3222
3223 if (D->hasAttr<DeprecatedAttr>())
3224 return CXAvailability_Deprecated;
3225 }
3226
3227 return CXAvailability_Available;
3228}
3229
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003230CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3231 if (clang_isDeclaration(cursor.kind))
3232 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3233
3234 return CXLanguage_Invalid;
3235}
3236} // end: extern "C"
3237
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003238
3239//===----------------------------------------------------------------------===//
3240// C++ AST instrospection.
3241//===----------------------------------------------------------------------===//
3242
3243extern "C" {
3244unsigned clang_CXXMethod_isStatic(CXCursor C) {
3245 if (!clang_isDeclaration(C.kind))
3246 return 0;
3247 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
3248 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003249}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003250
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003251} // end: extern "C"
3252
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003253//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003254// Attribute introspection.
3255//===----------------------------------------------------------------------===//
3256
3257extern "C" {
3258CXType clang_getIBOutletCollectionType(CXCursor C) {
3259 if (C.kind != CXCursor_IBOutletCollectionAttr)
3260 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3261
3262 IBOutletCollectionAttr *A =
3263 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3264
3265 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3266}
3267} // end: extern "C"
3268
3269//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003270// CXString Operations.
3271//===----------------------------------------------------------------------===//
3272
3273extern "C" {
3274const char *clang_getCString(CXString string) {
3275 return string.Spelling;
3276}
3277
3278void clang_disposeString(CXString string) {
3279 if (string.MustFreeString && string.Spelling)
3280 free((void*)string.Spelling);
3281}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003282
Ted Kremenekfb480492010-01-13 21:46:36 +00003283} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003284
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003285namespace clang { namespace cxstring {
3286CXString createCXString(const char *String, bool DupString){
3287 CXString Str;
3288 if (DupString) {
3289 Str.Spelling = strdup(String);
3290 Str.MustFreeString = 1;
3291 } else {
3292 Str.Spelling = String;
3293 Str.MustFreeString = 0;
3294 }
3295 return Str;
3296}
3297
3298CXString createCXString(llvm::StringRef String, bool DupString) {
3299 CXString Result;
3300 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3301 char *Spelling = (char *)malloc(String.size() + 1);
3302 memmove(Spelling, String.data(), String.size());
3303 Spelling[String.size()] = 0;
3304 Result.Spelling = Spelling;
3305 Result.MustFreeString = 1;
3306 } else {
3307 Result.Spelling = String.data();
3308 Result.MustFreeString = 0;
3309 }
3310 return Result;
3311}
3312}}
3313
Ted Kremenek04bb7162010-01-22 22:44:15 +00003314//===----------------------------------------------------------------------===//
3315// Misc. utility functions.
3316//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003317
Ted Kremenek04bb7162010-01-22 22:44:15 +00003318extern "C" {
3319
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003320CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003321 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003322}
3323
3324} // end: extern "C"