blob: 89816acfa63e50e37af19742bb7ef6c08c932cb4 [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 Gregor0ab1e9f2010-09-01 17:32:36 +0000293 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000294 bool VisitClassTemplatePartialSpecializationDecl(
295 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000296 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000297 bool VisitEnumConstantDecl(EnumConstantDecl *D);
298 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
299 bool VisitFunctionDecl(FunctionDecl *ND);
300 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000301 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000302 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000303 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000304 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000305 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000306 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
307 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
308 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
309 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000310 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000311 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
312 bool VisitObjCImplDecl(ObjCImplDecl *D);
313 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
314 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
315 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
316 // etc.
317 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
318 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
319 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000320 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000321 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000322 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000323 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000324 bool VisitUsingDecl(UsingDecl *D);
325 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
326 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000327
Douglas Gregor01829d32010-08-31 14:41:23 +0000328 // Name visitor
329 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000330 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000331
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000332 // Template visitors
333 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000334 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000335 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
336
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000337 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000338 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000339 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000340 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000341 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
342 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000343 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000344 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000345 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000346 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
347 bool VisitPointerTypeLoc(PointerTypeLoc TL);
348 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
349 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
350 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
351 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000352 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000353 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000354 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000355 // FIXME: Implement visitors here when the unimplemented TypeLocs get
356 // implemented
357 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
358 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000359
Douglas Gregora59e3902010-01-21 23:27:09 +0000360 // Statement visitors
361 bool VisitStmt(Stmt *S);
362 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000363 // FIXME: LabelStmt label?
364 bool VisitIfStmt(IfStmt *S);
365 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000366 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000367 bool VisitWhileStmt(WhileStmt *S);
368 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000369// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000370
Douglas Gregor336fd812010-01-23 00:40:08 +0000371 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000372 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000373 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000374 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000375 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000376 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000377 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000378 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000379 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000380 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfbb4c982010-09-02 21:07:44 +0000381 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000382 // FIXME: AddrLabelExpr (once we have cursors for labels)
383 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
384 bool VisitVAArgExpr(VAArgExpr *E);
385 // FIXME: InitListExpr (for the designators)
386 // FIXME: DesignatedInitExpr
Douglas Gregor94802292010-09-02 21:20:16 +0000387 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000388 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Steve Naroff89922f82009-08-31 00:59:03 +0000389};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000390
Ted Kremenekab188932010-01-05 19:32:54 +0000391} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000392
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000393static SourceRange getRawCursorExtent(CXCursor C);
394
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000395RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000396 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
397}
398
Douglas Gregorb1373d02010-01-20 20:59:29 +0000399/// \brief Visit the given cursor and, if requested by the visitor,
400/// its children.
401///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000402/// \param Cursor the cursor to visit.
403///
404/// \param CheckRegionOfInterest if true, then the caller already checked that
405/// this cursor is within the region of interest.
406///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407/// \returns true if the visitation should be aborted, false if it
408/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000409bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000410 if (clang_isInvalid(Cursor.kind))
411 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000412
Douglas Gregorb1373d02010-01-20 20:59:29 +0000413 if (clang_isDeclaration(Cursor.kind)) {
414 Decl *D = getCursorDecl(Cursor);
415 assert(D && "Invalid declaration cursor");
416 if (D->getPCHLevel() > MaxPCHLevel)
417 return false;
418
419 if (D->isImplicit())
420 return false;
421 }
422
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000423 // If we have a range of interest, and this cursor doesn't intersect with it,
424 // we're done.
425 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000426 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000427 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000428 return false;
429 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000430
Douglas Gregorb1373d02010-01-20 20:59:29 +0000431 switch (Visitor(Cursor, Parent, ClientData)) {
432 case CXChildVisit_Break:
433 return true;
434
435 case CXChildVisit_Continue:
436 return false;
437
438 case CXChildVisit_Recurse:
439 return VisitChildren(Cursor);
440 }
441
Douglas Gregorfd643772010-01-25 16:45:46 +0000442 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000443}
444
Douglas Gregor788f5a12010-03-20 00:41:21 +0000445std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
446CursorVisitor::getPreprocessedEntities() {
447 PreprocessingRecord &PPRec
448 = *TU->getPreprocessor().getPreprocessingRecord();
449
450 bool OnlyLocalDecls
451 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
452
453 // There is no region of interest; we have to walk everything.
454 if (RegionOfInterest.isInvalid())
455 return std::make_pair(PPRec.begin(OnlyLocalDecls),
456 PPRec.end(OnlyLocalDecls));
457
458 // Find the file in which the region of interest lands.
459 SourceManager &SM = TU->getSourceManager();
460 std::pair<FileID, unsigned> Begin
461 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
462 std::pair<FileID, unsigned> End
463 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
464
465 // The region of interest spans files; we have to walk everything.
466 if (Begin.first != End.first)
467 return std::make_pair(PPRec.begin(OnlyLocalDecls),
468 PPRec.end(OnlyLocalDecls));
469
470 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
471 = TU->getPreprocessedEntitiesByFile();
472 if (ByFileMap.empty()) {
473 // Build the mapping from files to sets of preprocessed entities.
474 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
475 EEnd = PPRec.end(OnlyLocalDecls);
476 E != EEnd; ++E) {
477 std::pair<FileID, unsigned> P
478 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
479 ByFileMap[P.first].push_back(*E);
480 }
481 }
482
483 return std::make_pair(ByFileMap[Begin.first].begin(),
484 ByFileMap[Begin.first].end());
485}
486
Douglas Gregorb1373d02010-01-20 20:59:29 +0000487/// \brief Visit the children of the given cursor.
488///
489/// \returns true if the visitation should be aborted, false if it
490/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000491bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000492 if (clang_isReference(Cursor.kind)) {
493 // By definition, references have no children.
494 return false;
495 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000496
497 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000498 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000499 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000500
Douglas Gregorb1373d02010-01-20 20:59:29 +0000501 if (clang_isDeclaration(Cursor.kind)) {
502 Decl *D = getCursorDecl(Cursor);
503 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000504 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000505 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000506
Douglas Gregora59e3902010-01-21 23:27:09 +0000507 if (clang_isStatement(Cursor.kind))
508 return Visit(getCursorStmt(Cursor));
509 if (clang_isExpression(Cursor.kind))
510 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000511
Douglas Gregorb1373d02010-01-20 20:59:29 +0000512 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000513 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000514 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
515 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000516 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
517 TLEnd = CXXUnit->top_level_end();
518 TL != TLEnd; ++TL) {
519 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000520 return true;
521 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000522 } else if (VisitDeclContext(
523 CXXUnit->getASTContext().getTranslationUnitDecl()))
524 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000525
Douglas Gregor0396f462010-03-19 05:22:59 +0000526 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000527 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000528 // FIXME: Once we have the ability to deserialize a preprocessing record,
529 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000530 PreprocessingRecord::iterator E, EEnd;
531 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000532 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
533 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
534 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000535
Douglas Gregor0396f462010-03-19 05:22:59 +0000536 continue;
537 }
538
539 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
540 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
541 return true;
542
543 continue;
544 }
545 }
546 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000547 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000548 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000549
Douglas Gregorb1373d02010-01-20 20:59:29 +0000550 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000551 return false;
552}
553
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000554bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000555 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
556 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000557
Ted Kremenek664cffd2010-07-22 11:30:19 +0000558 if (Stmt *Body = B->getBody())
559 return Visit(MakeCXCursor(Body, StmtParent, TU));
560
561 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000562}
563
Douglas Gregorb1373d02010-01-20 20:59:29 +0000564bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000565 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000566 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000567
Ted Kremenek23173d72010-05-18 21:09:07 +0000568 Decl *D = *I;
569 if (D->getLexicalDeclContext() != DC)
570 continue;
571
572 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000573
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000574 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000575 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000576 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000577 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000578
579 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000580 case RangeBefore:
581 // This declaration comes before the region of interest; skip it.
582 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000583
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000584 case RangeAfter:
585 // This declaration comes after the region of interest; we're done.
586 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000587
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000588 case RangeOverlap:
589 // This declaration overlaps the region of interest; visit it.
590 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000591 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000592 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000593
Daniel Dunbard52864b2010-02-14 10:02:57 +0000594 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000595 return true;
596 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000597
Douglas Gregorb1373d02010-01-20 20:59:29 +0000598 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000599}
600
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000601bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
602 llvm_unreachable("Translation units are visited directly by Visit()");
603 return false;
604}
605
606bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
607 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
608 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000609
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000610 return false;
611}
612
613bool CursorVisitor::VisitTagDecl(TagDecl *D) {
614 return VisitDeclContext(D);
615}
616
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000617bool CursorVisitor::VisitClassTemplateSpecializationDecl(
618 ClassTemplateSpecializationDecl *D) {
619 bool ShouldVisitBody = false;
620 switch (D->getSpecializationKind()) {
621 case TSK_Undeclared:
622 case TSK_ImplicitInstantiation:
623 // Nothing to visit
624 return false;
625
626 case TSK_ExplicitInstantiationDeclaration:
627 case TSK_ExplicitInstantiationDefinition:
628 break;
629
630 case TSK_ExplicitSpecialization:
631 ShouldVisitBody = true;
632 break;
633 }
634
635 // Visit the template arguments used in the specialization.
636 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
637 TypeLoc TL = SpecType->getTypeLoc();
638 if (TemplateSpecializationTypeLoc *TSTLoc
639 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
640 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
641 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
642 return true;
643 }
644 }
645
646 if (ShouldVisitBody && VisitCXXRecordDecl(D))
647 return true;
648
649 return false;
650}
651
Douglas Gregor74dbe642010-08-31 19:31:58 +0000652bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
653 ClassTemplatePartialSpecializationDecl *D) {
654 // FIXME: Visit the "outer" template parameter lists on the TagDecl
655 // before visiting these template parameters.
656 if (VisitTemplateParameters(D->getTemplateParameters()))
657 return true;
658
659 // Visit the partial specialization arguments.
660 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
661 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
662 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
663 return true;
664
665 return VisitCXXRecordDecl(D);
666}
667
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000668bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000669 // Visit the default argument.
670 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
671 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
672 if (Visit(DefArg->getTypeLoc()))
673 return true;
674
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000675 return false;
676}
677
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000678bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
679 if (Expr *Init = D->getInitExpr())
680 return Visit(MakeCXCursor(Init, StmtParent, TU));
681 return false;
682}
683
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000684bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
685 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
686 if (Visit(TSInfo->getTypeLoc()))
687 return true;
688
689 return false;
690}
691
Douglas Gregorb1373d02010-01-20 20:59:29 +0000692bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000693 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
694 // Visit the function declaration's syntactic components in the order
695 // written. This requires a bit of work.
696 TypeLoc TL = TSInfo->getTypeLoc();
697 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
698
699 // If we have a function declared directly (without the use of a typedef),
700 // visit just the return type. Otherwise, just visit the function's type
701 // now.
702 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
703 (!FTL && Visit(TL)))
704 return true;
705
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000706 // Visit the nested-name-specifier, if present.
707 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
708 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
709 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000710
711 // Visit the declaration name.
712 if (VisitDeclarationNameInfo(ND->getNameInfo()))
713 return true;
714
715 // FIXME: Visit explicitly-specified template arguments!
716
717 // Visit the function parameters, if we have a function type.
718 if (FTL && VisitFunctionTypeLoc(*FTL, true))
719 return true;
720
721 // FIXME: Attributes?
722 }
723
Douglas Gregora59e3902010-01-21 23:27:09 +0000724 if (ND->isThisDeclarationADefinition() &&
725 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
726 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000727
Douglas Gregorb1373d02010-01-20 20:59:29 +0000728 return false;
729}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000730
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000731bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
732 if (VisitDeclaratorDecl(D))
733 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000734
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000735 if (Expr *BitWidth = D->getBitWidth())
736 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000737
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000738 return false;
739}
740
741bool CursorVisitor::VisitVarDecl(VarDecl *D) {
742 if (VisitDeclaratorDecl(D))
743 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000744
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000745 if (Expr *Init = D->getInit())
746 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000747
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000748 return false;
749}
750
Douglas Gregor84b51d72010-09-01 20:16:53 +0000751bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
752 if (VisitDeclaratorDecl(D))
753 return true;
754
755 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
756 if (Expr *DefArg = D->getDefaultArgument())
757 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
758
759 return false;
760}
761
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000762bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
763 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
764 // before visiting these template parameters.
765 if (VisitTemplateParameters(D->getTemplateParameters()))
766 return true;
767
768 return VisitFunctionDecl(D->getTemplatedDecl());
769}
770
Douglas Gregor39d6f072010-08-31 19:02:00 +0000771bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
772 // FIXME: Visit the "outer" template parameter lists on the TagDecl
773 // before visiting these template parameters.
774 if (VisitTemplateParameters(D->getTemplateParameters()))
775 return true;
776
777 return VisitCXXRecordDecl(D->getTemplatedDecl());
778}
779
Douglas Gregor84b51d72010-09-01 20:16:53 +0000780bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
781 if (VisitTemplateParameters(D->getTemplateParameters()))
782 return true;
783
784 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
785 VisitTemplateArgumentLoc(D->getDefaultArgument()))
786 return true;
787
788 return false;
789}
790
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000791bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000792 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
793 if (Visit(TSInfo->getTypeLoc()))
794 return true;
795
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797 PEnd = ND->param_end();
798 P != PEnd; ++P) {
799 if (Visit(MakeCXCursor(*P, TU)))
800 return true;
801 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000802
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000803 if (ND->isThisDeclarationADefinition() &&
804 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
805 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000806
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000807 return false;
808}
809
Douglas Gregora59e3902010-01-21 23:27:09 +0000810bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
811 return VisitDeclContext(D);
812}
813
Douglas Gregorb1373d02010-01-20 20:59:29 +0000814bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000815 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
816 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000817 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000818
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000819 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
820 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
821 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000822 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000823 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000824
Douglas Gregora59e3902010-01-21 23:27:09 +0000825 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000826}
827
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000828bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
829 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
830 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
831 E = PID->protocol_end(); I != E; ++I, ++PL)
832 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
833 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000834
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000835 return VisitObjCContainerDecl(PID);
836}
837
Ted Kremenek23173d72010-05-18 21:09:07 +0000838bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000839 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
840 return true;
841
Ted Kremenek23173d72010-05-18 21:09:07 +0000842 // FIXME: This implements a workaround with @property declarations also being
843 // installed in the DeclContext for the @interface. Eventually this code
844 // should be removed.
845 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
846 if (!CDecl || !CDecl->IsClassExtension())
847 return false;
848
849 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
850 if (!ID)
851 return false;
852
853 IdentifierInfo *PropertyId = PD->getIdentifier();
854 ObjCPropertyDecl *prevDecl =
855 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
856
857 if (!prevDecl)
858 return false;
859
860 // Visit synthesized methods since they will be skipped when visiting
861 // the @interface.
862 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
863 if (MD->isSynthesized())
864 if (Visit(MakeCXCursor(MD, TU)))
865 return true;
866
867 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
868 if (MD->isSynthesized())
869 if (Visit(MakeCXCursor(MD, TU)))
870 return true;
871
872 return false;
873}
874
Douglas Gregorb1373d02010-01-20 20:59:29 +0000875bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000876 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000877 if (D->getSuperClass() &&
878 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000879 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000880 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000881 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000882
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000883 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
884 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
885 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000886 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000887 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000888
Douglas Gregora59e3902010-01-21 23:27:09 +0000889 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000890}
891
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000892bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
893 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000894}
895
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000896bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000897 // 'ID' could be null when dealing with invalid code.
898 if (ObjCInterfaceDecl *ID = D->getClassInterface())
899 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
900 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000901
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000902 return VisitObjCImplDecl(D);
903}
904
905bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
906#if 0
907 // Issue callbacks for super class.
908 // FIXME: No source location information!
909 if (D->getSuperClass() &&
910 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000911 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000912 TU)))
913 return true;
914#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000915
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000916 return VisitObjCImplDecl(D);
917}
918
919bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
920 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
921 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
922 E = D->protocol_end();
923 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000924 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000925 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000926
927 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000928}
929
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000930bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
931 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
932 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
933 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000934
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000935 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000936}
937
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000938bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
939 return VisitDeclContext(D);
940}
941
Douglas Gregor69319002010-08-31 23:48:11 +0000942bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000943 // Visit nested-name-specifier.
944 if (NestedNameSpecifier *Qualifier = D->getQualifier())
945 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
946 return true;
Douglas Gregor69319002010-08-31 23:48:11 +0000947
948 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
949 D->getTargetNameLoc(), TU));
950}
951
Douglas Gregor7e242562010-09-01 19:52:22 +0000952bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000953 // Visit nested-name-specifier.
954 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
955 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
956 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +0000957
958 // FIXME: Provide a multi-reference of some kind for all of the declarations
959 // that the using declaration refers to. We don't have this kind of cursor
960 // yet.
961
962 return VisitDeclarationNameInfo(D->getNameInfo());
963}
964
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000965bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000966 // Visit nested-name-specifier.
967 if (NestedNameSpecifier *Qualifier = D->getQualifier())
968 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
969 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000970
971 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
972 D->getIdentLocation(), TU));
973}
974
Douglas Gregor7e242562010-09-01 19:52:22 +0000975bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000976 // Visit nested-name-specifier.
977 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
978 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
979 return true;
980
Douglas Gregor7e242562010-09-01 19:52:22 +0000981 return VisitDeclarationNameInfo(D->getNameInfo());
982}
983
984bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
985 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000986 // Visit nested-name-specifier.
987 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
988 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
989 return true;
990
Douglas Gregor7e242562010-09-01 19:52:22 +0000991 return false;
992}
993
Douglas Gregor01829d32010-08-31 14:41:23 +0000994bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
995 switch (Name.getName().getNameKind()) {
996 case clang::DeclarationName::Identifier:
997 case clang::DeclarationName::CXXLiteralOperatorName:
998 case clang::DeclarationName::CXXOperatorName:
999 case clang::DeclarationName::CXXUsingDirective:
1000 return false;
1001
1002 case clang::DeclarationName::CXXConstructorName:
1003 case clang::DeclarationName::CXXDestructorName:
1004 case clang::DeclarationName::CXXConversionFunctionName:
1005 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1006 return Visit(TSInfo->getTypeLoc());
1007 return false;
1008
1009 case clang::DeclarationName::ObjCZeroArgSelector:
1010 case clang::DeclarationName::ObjCOneArgSelector:
1011 case clang::DeclarationName::ObjCMultiArgSelector:
1012 // FIXME: Per-identifier location info?
1013 return false;
1014 }
1015
1016 return false;
1017}
1018
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001019bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1020 SourceRange Range) {
1021 // FIXME: This whole routine is a hack to work around the lack of proper
1022 // source information in nested-name-specifiers (PR5791). Since we do have
1023 // a beginning source location, we can visit the first component of the
1024 // nested-name-specifier, if it's a single-token component.
1025 if (!NNS)
1026 return false;
1027
1028 // Get the first component in the nested-name-specifier.
1029 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1030 NNS = Prefix;
1031
1032 switch (NNS->getKind()) {
1033 case NestedNameSpecifier::Namespace:
1034 // FIXME: The token at this source location might actually have been a
1035 // namespace alias, but we don't model that. Lame!
1036 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1037 TU));
1038
1039 case NestedNameSpecifier::TypeSpec: {
1040 // If the type has a form where we know that the beginning of the source
1041 // range matches up with a reference cursor. Visit the appropriate reference
1042 // cursor.
1043 Type *T = NNS->getAsType();
1044 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1045 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1046 if (const TagType *Tag = dyn_cast<TagType>(T))
1047 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1048 if (const TemplateSpecializationType *TST
1049 = dyn_cast<TemplateSpecializationType>(T))
1050 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1051 break;
1052 }
1053
1054 case NestedNameSpecifier::TypeSpecWithTemplate:
1055 case NestedNameSpecifier::Global:
1056 case NestedNameSpecifier::Identifier:
1057 break;
1058 }
1059
1060 return false;
1061}
1062
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001063bool CursorVisitor::VisitTemplateParameters(
1064 const TemplateParameterList *Params) {
1065 if (!Params)
1066 return false;
1067
1068 for (TemplateParameterList::const_iterator P = Params->begin(),
1069 PEnd = Params->end();
1070 P != PEnd; ++P) {
1071 if (Visit(MakeCXCursor(*P, TU)))
1072 return true;
1073 }
1074
1075 return false;
1076}
1077
Douglas Gregor0b36e612010-08-31 20:37:03 +00001078bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1079 switch (Name.getKind()) {
1080 case TemplateName::Template:
1081 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1082
1083 case TemplateName::OverloadedTemplate:
1084 // FIXME: We need a way to return multiple lookup results in a single
1085 // cursor.
1086 return false;
1087
1088 case TemplateName::DependentTemplate:
1089 // FIXME: Visit nested-name-specifier.
1090 return false;
1091
1092 case TemplateName::QualifiedTemplate:
1093 // FIXME: Visit nested-name-specifier.
1094 return Visit(MakeCursorTemplateRef(
1095 Name.getAsQualifiedTemplateName()->getDecl(),
1096 Loc, TU));
1097 }
1098
1099 return false;
1100}
1101
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001102bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1103 switch (TAL.getArgument().getKind()) {
1104 case TemplateArgument::Null:
1105 case TemplateArgument::Integral:
1106 return false;
1107
1108 case TemplateArgument::Pack:
1109 // FIXME: Implement when variadic templates come along.
1110 return false;
1111
1112 case TemplateArgument::Type:
1113 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1114 return Visit(TSInfo->getTypeLoc());
1115 return false;
1116
1117 case TemplateArgument::Declaration:
1118 if (Expr *E = TAL.getSourceDeclExpression())
1119 return Visit(MakeCXCursor(E, StmtParent, TU));
1120 return false;
1121
1122 case TemplateArgument::Expression:
1123 if (Expr *E = TAL.getSourceExpression())
1124 return Visit(MakeCXCursor(E, StmtParent, TU));
1125 return false;
1126
1127 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001128 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1129 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001130 }
1131
1132 return false;
1133}
1134
Ted Kremeneka0536d82010-05-07 01:04:29 +00001135bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1136 return VisitDeclContext(D);
1137}
1138
Douglas Gregor01829d32010-08-31 14:41:23 +00001139bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1140 return Visit(TL.getUnqualifiedLoc());
1141}
1142
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001143bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1144 ASTContext &Context = TU->getASTContext();
1145
1146 // Some builtin types (such as Objective-C's "id", "sel", and
1147 // "Class") have associated declarations. Create cursors for those.
1148 QualType VisitType;
1149 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001150 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001151 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001152 case BuiltinType::Char_U:
1153 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001154 case BuiltinType::Char16:
1155 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001156 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001157 case BuiltinType::UInt:
1158 case BuiltinType::ULong:
1159 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001160 case BuiltinType::UInt128:
1161 case BuiltinType::Char_S:
1162 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001163 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001164 case BuiltinType::Short:
1165 case BuiltinType::Int:
1166 case BuiltinType::Long:
1167 case BuiltinType::LongLong:
1168 case BuiltinType::Int128:
1169 case BuiltinType::Float:
1170 case BuiltinType::Double:
1171 case BuiltinType::LongDouble:
1172 case BuiltinType::NullPtr:
1173 case BuiltinType::Overload:
1174 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001175 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001176
1177 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001178 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001179
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001180 case BuiltinType::ObjCId:
1181 VisitType = Context.getObjCIdType();
1182 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001183
1184 case BuiltinType::ObjCClass:
1185 VisitType = Context.getObjCClassType();
1186 break;
1187
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001188 case BuiltinType::ObjCSel:
1189 VisitType = Context.getObjCSelType();
1190 break;
1191 }
1192
1193 if (!VisitType.isNull()) {
1194 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001195 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001196 TU));
1197 }
1198
1199 return false;
1200}
1201
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001202bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1203 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1204}
1205
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001206bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1207 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1208}
1209
1210bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1211 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1212}
1213
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001214bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1215 // FIXME: We can't visit the template template parameter, but there's
1216 // no context information with which we can match up the depth/index in the
1217 // type to the appropriate
1218 return false;
1219}
1220
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001221bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1222 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1223 return true;
1224
John McCallc12c5bb2010-05-15 11:32:37 +00001225 return false;
1226}
1227
1228bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1229 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1230 return true;
1231
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001232 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1233 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1234 TU)))
1235 return true;
1236 }
1237
1238 return false;
1239}
1240
1241bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001242 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001243}
1244
1245bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1246 return Visit(TL.getPointeeLoc());
1247}
1248
1249bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1250 return Visit(TL.getPointeeLoc());
1251}
1252
1253bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1254 return Visit(TL.getPointeeLoc());
1255}
1256
1257bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001258 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001259}
1260
1261bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001262 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001263}
1264
Douglas Gregor01829d32010-08-31 14:41:23 +00001265bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1266 bool SkipResultType) {
1267 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001268 return true;
1269
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001270 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001271 if (Decl *D = TL.getArg(I))
1272 if (Visit(MakeCXCursor(D, TU)))
1273 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001274
1275 return false;
1276}
1277
1278bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1279 if (Visit(TL.getElementLoc()))
1280 return true;
1281
1282 if (Expr *Size = TL.getSizeExpr())
1283 return Visit(MakeCXCursor(Size, StmtParent, TU));
1284
1285 return false;
1286}
1287
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001288bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1289 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001290 // Visit the template name.
1291 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1292 TL.getTemplateNameLoc()))
1293 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001294
1295 // Visit the template arguments.
1296 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1297 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1298 return true;
1299
1300 return false;
1301}
1302
Douglas Gregor2332c112010-01-21 20:48:56 +00001303bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1304 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1305}
1306
1307bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1308 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1309 return Visit(TSInfo->getTypeLoc());
1310
1311 return false;
1312}
1313
Douglas Gregora59e3902010-01-21 23:27:09 +00001314bool CursorVisitor::VisitStmt(Stmt *S) {
1315 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1316 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001317 if (Stmt *C = *Child)
1318 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1319 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001320 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001321
Douglas Gregora59e3902010-01-21 23:27:09 +00001322 return false;
1323}
1324
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001325bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1326 // Specially handle CaseStmts because they can be nested, e.g.:
1327 //
1328 // case 1:
1329 // case 2:
1330 //
1331 // In this case the second CaseStmt is the child of the first. Walking
1332 // these recursively can blow out the stack.
1333 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1334 while (true) {
1335 // Set the Parent field to Cursor, then back to its old value once we're
1336 // done.
1337 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1338
1339 if (Stmt *LHS = S->getLHS())
1340 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1341 return true;
1342 if (Stmt *RHS = S->getRHS())
1343 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1344 return true;
1345 if (Stmt *SubStmt = S->getSubStmt()) {
1346 if (!isa<CaseStmt>(SubStmt))
1347 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1348
1349 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1350 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1351 Cursor = MakeCXCursor(CS, StmtParent, TU);
1352 if (RegionOfInterest.isValid()) {
1353 SourceRange Range = CS->getSourceRange();
1354 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1355 return false;
1356 }
1357
1358 switch (Visitor(Cursor, Parent, ClientData)) {
1359 case CXChildVisit_Break: return true;
1360 case CXChildVisit_Continue: return false;
1361 case CXChildVisit_Recurse:
1362 // Perform tail-recursion manually.
1363 S = CS;
1364 continue;
1365 }
1366 }
1367 return false;
1368 }
1369}
1370
Douglas Gregora59e3902010-01-21 23:27:09 +00001371bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1372 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1373 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001374 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001375 return true;
1376 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001377
Douglas Gregora59e3902010-01-21 23:27:09 +00001378 return false;
1379}
1380
Douglas Gregorf5bab412010-01-22 01:00:11 +00001381bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1382 if (VarDecl *Var = S->getConditionVariable()) {
1383 if (Visit(MakeCXCursor(Var, TU)))
1384 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001385 }
1386
Douglas Gregor263b47b2010-01-25 16:12:32 +00001387 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1388 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001389 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1390 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001391 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1392 return true;
1393
1394 return false;
1395}
1396
1397bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1398 if (VarDecl *Var = S->getConditionVariable()) {
1399 if (Visit(MakeCXCursor(Var, TU)))
1400 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001401 }
1402
Douglas Gregor263b47b2010-01-25 16:12:32 +00001403 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1404 return true;
1405 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1406 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001407
Douglas Gregor263b47b2010-01-25 16:12:32 +00001408 return false;
1409}
1410
1411bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1412 if (VarDecl *Var = S->getConditionVariable()) {
1413 if (Visit(MakeCXCursor(Var, TU)))
1414 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001415 }
1416
Douglas Gregor263b47b2010-01-25 16:12:32 +00001417 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1418 return true;
1419 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001420 return true;
1421
Douglas Gregor263b47b2010-01-25 16:12:32 +00001422 return false;
1423}
1424
1425bool CursorVisitor::VisitForStmt(ForStmt *S) {
1426 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1427 return true;
1428 if (VarDecl *Var = S->getConditionVariable()) {
1429 if (Visit(MakeCXCursor(Var, TU)))
1430 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001431 }
1432
Douglas Gregor263b47b2010-01-25 16:12:32 +00001433 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1434 return true;
1435 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1436 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001437 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1438 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001439
Douglas Gregorf5bab412010-01-22 01:00:11 +00001440 return false;
1441}
1442
Douglas Gregor8947a752010-09-02 20:35:02 +00001443bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1444 // Visit nested-name-specifier, if present.
1445 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1446 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1447 return true;
1448
1449 // Visit declaration name.
1450 if (VisitDeclarationNameInfo(E->getNameInfo()))
1451 return true;
1452
1453 // Visit explicitly-specified template arguments.
1454 if (E->hasExplicitTemplateArgs()) {
1455 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1456 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1457 *ArgEnd = Arg + Args.NumTemplateArgs;
1458 Arg != ArgEnd; ++Arg)
1459 if (VisitTemplateArgumentLoc(*Arg))
1460 return true;
1461 }
1462
1463 return false;
1464}
1465
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001466bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1467 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1468 return true;
1469
1470 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1471 return true;
1472
1473 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1474 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1475 return true;
1476
1477 return false;
1478}
1479
Ted Kremenek3064ef92010-08-27 21:34:58 +00001480bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1481 if (D->isDefinition()) {
1482 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1483 E = D->bases_end(); I != E; ++I) {
1484 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1485 return true;
1486 }
1487 }
1488
1489 return VisitTagDecl(D);
1490}
1491
1492
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001493bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1494 return Visit(B->getBlockDecl());
1495}
1496
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001497bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1498 // FIXME: Visit fields as well?
1499 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1500 return true;
1501
1502 return VisitExpr(E);
1503}
1504
Douglas Gregor336fd812010-01-23 00:40:08 +00001505bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1506 if (E->isArgumentType()) {
1507 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1508 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001509
Douglas Gregor336fd812010-01-23 00:40:08 +00001510 return false;
1511 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001512
Douglas Gregor336fd812010-01-23 00:40:08 +00001513 return VisitExpr(E);
1514}
1515
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001516bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1517 // Visit the base expression.
1518 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1519 return true;
1520
1521 // Visit the nested-name-specifier
1522 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1523 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1524 return true;
1525
1526 // Visit the declaration name.
1527 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1528 return true;
1529
1530 // Visit the explicitly-specified template arguments, if any.
1531 if (E->hasExplicitTemplateArgs()) {
1532 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1533 *ArgEnd = Arg + E->getNumTemplateArgs();
1534 Arg != ArgEnd;
1535 ++Arg) {
1536 if (VisitTemplateArgumentLoc(*Arg))
1537 return true;
1538 }
1539 }
1540
1541 return false;
1542}
1543
Douglas Gregor336fd812010-01-23 00:40:08 +00001544bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1545 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1546 if (Visit(TSInfo->getTypeLoc()))
1547 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001548
Douglas Gregor336fd812010-01-23 00:40:08 +00001549 return VisitCastExpr(E);
1550}
1551
1552bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1553 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1554 if (Visit(TSInfo->getTypeLoc()))
1555 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001556
Douglas Gregor336fd812010-01-23 00:40:08 +00001557 return VisitExpr(E);
1558}
1559
Douglas Gregor648220e2010-08-10 15:02:34 +00001560bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1561 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1562 Visit(E->getArgTInfo2()->getTypeLoc());
1563}
1564
1565bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1566 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1567 return true;
1568
1569 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1570}
1571
Douglas Gregor94802292010-09-02 21:20:16 +00001572bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1573 if (E->isTypeOperand()) {
1574 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1575 return Visit(TSInfo->getTypeLoc());
1576
1577 return false;
1578 }
1579
1580 return VisitExpr(E);
1581}
1582
Douglas Gregorc2350e52010-03-08 16:40:19 +00001583bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001584 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1585 if (Visit(TSInfo->getTypeLoc()))
1586 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001587
1588 return VisitExpr(E);
1589}
1590
Douglas Gregor81d34662010-04-20 15:39:42 +00001591bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1592 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1593}
1594
1595
Ted Kremenek09dfa372010-02-18 05:46:33 +00001596bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001597 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1598 i != e; ++i)
1599 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001600 return true;
1601
1602 return false;
1603}
1604
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001605extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001606CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1607 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001608 // We use crash recovery to make some of our APIs more reliable, implicitly
1609 // enable it.
1610 llvm::CrashRecoveryContext::Enable();
1611
Douglas Gregora030b7c2010-01-22 20:35:53 +00001612 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001613 if (excludeDeclarationsFromPCH)
1614 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001615 if (displayDiagnostics)
1616 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001617 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001618}
1619
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001620void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001621 if (CIdx)
1622 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001623 if (getenv("LIBCLANG_TIMING"))
1624 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001625}
1626
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001627void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001628 if (CIdx) {
1629 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1630 CXXIdx->setUseExternalASTGeneration(value);
1631 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001632}
1633
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001634CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001635 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001636 if (!CIdx)
1637 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001638
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001639 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001640
Douglas Gregor28019772010-04-05 23:52:57 +00001641 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001642 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001643 CXXIdx->getOnlyLocalDecls(),
1644 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001645}
1646
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001647unsigned clang_defaultEditingTranslationUnitOptions() {
1648 return CXTranslationUnit_PrecompiledPreamble;
1649}
1650
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001651CXTranslationUnit
1652clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1653 const char *source_filename,
1654 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001655 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001656 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001657 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001658 return clang_parseTranslationUnit(CIdx, source_filename,
1659 command_line_args, num_command_line_args,
1660 unsaved_files, num_unsaved_files,
1661 CXTranslationUnit_DetailedPreprocessingRecord);
1662}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001663
1664struct ParseTranslationUnitInfo {
1665 CXIndex CIdx;
1666 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001667 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001668 int num_command_line_args;
1669 struct CXUnsavedFile *unsaved_files;
1670 unsigned num_unsaved_files;
1671 unsigned options;
1672 CXTranslationUnit result;
1673};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001674static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001675 ParseTranslationUnitInfo *PTUI =
1676 static_cast<ParseTranslationUnitInfo*>(UserData);
1677 CXIndex CIdx = PTUI->CIdx;
1678 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001679 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001680 int num_command_line_args = PTUI->num_command_line_args;
1681 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1682 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1683 unsigned options = PTUI->options;
1684 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001685
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001686 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001687 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001688
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001689 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1690
Douglas Gregor44c181a2010-07-23 00:33:23 +00001691 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001692 bool CompleteTranslationUnit
1693 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001694 bool CacheCodeCompetionResults
1695 = options & CXTranslationUnit_CacheCompletionResults;
1696
Douglas Gregor5352ac02010-01-28 00:27:43 +00001697 // Configure the diagnostics.
1698 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001699 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1700 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001701
Douglas Gregor4db64a42010-01-23 00:14:00 +00001702 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1703 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001704 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001705 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001706 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001707 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1708 Buffer));
1709 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001710
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001711 if (!CXXIdx->getUseExternalASTGeneration()) {
1712 llvm::SmallVector<const char *, 16> Args;
1713
1714 // The 'source_filename' argument is optional. If the caller does not
1715 // specify it then it is assumed that the source file is specified
1716 // in the actual argument list.
1717 if (source_filename)
1718 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001719
1720 // Since the Clang C library is primarily used by batch tools dealing with
1721 // (often very broken) source code, where spell-checking can have a
1722 // significant negative impact on performance (particularly when
1723 // precompiled headers are involved), we disable it by default.
1724 // Note that we place this argument early in the list, so that it can be
1725 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001726 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001727
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001728 Args.insert(Args.end(), command_line_args,
1729 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001730
Douglas Gregor44c181a2010-07-23 00:33:23 +00001731 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001732 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1733 Args.push_back("-Xclang");
1734 Args.push_back("-detailed-preprocessing-record");
1735 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001736
Douglas Gregor5352ac02010-01-28 00:27:43 +00001737 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001738
Ted Kremenek29b72842010-01-07 22:49:05 +00001739#ifdef USE_CRASHTRACER
1740 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001741#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001742
Daniel Dunbar94220972009-12-05 02:17:18 +00001743 llvm::OwningPtr<ASTUnit> Unit(
1744 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001745 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001746 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001747 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001748 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001749 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001750 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001751 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001752 CompleteTranslationUnit,
1753 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001754
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001755 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001756 // Make sure to check that 'Unit' is non-NULL.
1757 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001758 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1759 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001760 D != DEnd; ++D) {
1761 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001762 CXString Msg = clang_formatDiagnostic(&Diag,
1763 clang_defaultDiagnosticDisplayOptions());
1764 fprintf(stderr, "%s\n", clang_getCString(Msg));
1765 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001766 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001767#ifdef LLVM_ON_WIN32
1768 // On Windows, force a flush, since there may be multiple copies of
1769 // stderr and stdout in the file system, all with different buffers
1770 // but writing to the same device.
1771 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001772#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001773 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001774 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001775
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001776 PTUI->result = Unit.take();
1777 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001778 }
1779
Ted Kremenek139ba862009-10-22 00:03:57 +00001780 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001781 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001782
Ted Kremenek139ba862009-10-22 00:03:57 +00001783 // First add the complete path to the 'clang' executable.
1784 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001785 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001786
Ted Kremenek139ba862009-10-22 00:03:57 +00001787 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001788 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001789
Ted Kremenek139ba862009-10-22 00:03:57 +00001790 // The 'source_filename' argument is optional. If the caller does not
1791 // specify it then it is assumed that the source file is specified
1792 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001793 if (source_filename)
1794 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001795
Steve Naroff37b5ac22009-10-15 20:50:09 +00001796 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001797 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001798 char astTmpFile[L_tmpnam];
1799 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001800
1801 // Since the Clang C library is primarily used by batch tools dealing with
1802 // (often very broken) source code, where spell-checking can have a
1803 // significant negative impact on performance (particularly when
1804 // precompiled headers are involved), we disable it by default.
1805 // Note that we place this argument early in the list, so that it can be
1806 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001807 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001808
Douglas Gregor4db64a42010-01-23 00:14:00 +00001809 // Remap any unsaved files to temporary files.
1810 std::vector<llvm::sys::Path> TemporaryFiles;
1811 std::vector<std::string> RemapArgs;
1812 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001813 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001814
Douglas Gregor4db64a42010-01-23 00:14:00 +00001815 // The pointers into the elements of RemapArgs are stable because we
1816 // won't be adding anything to RemapArgs after this point.
1817 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1818 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001819
Ted Kremenek139ba862009-10-22 00:03:57 +00001820 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1821 for (int i = 0; i < num_command_line_args; ++i)
1822 if (const char *arg = command_line_args[i]) {
1823 if (strcmp(arg, "-o") == 0) {
1824 ++i; // Also skip the matching argument.
1825 continue;
1826 }
1827 if (strcmp(arg, "-emit-ast") == 0 ||
1828 strcmp(arg, "-c") == 0 ||
1829 strcmp(arg, "-fsyntax-only") == 0) {
1830 continue;
1831 }
1832
1833 // Keep the argument.
1834 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001835 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001836
Douglas Gregord93256e2010-01-28 06:00:51 +00001837 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001838 char tmpFileResults[L_tmpnam];
1839 char *tmpResultsFileName = tmpnam(tmpFileResults);
1840 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001841 TemporaryFiles.push_back(DiagnosticsFile);
1842 argv.push_back("-fdiagnostics-binary");
1843
Douglas Gregor44c181a2010-07-23 00:33:23 +00001844 // Do we need the detailed preprocessing record?
1845 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1846 argv.push_back("-Xclang");
1847 argv.push_back("-detailed-preprocessing-record");
1848 }
1849
Ted Kremenek139ba862009-10-22 00:03:57 +00001850 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001851 argv.push_back(NULL);
1852
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001853 // Invoke 'clang'.
1854 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1855 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001856 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001857 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1858 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001859 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001860 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001861 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001862
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001863 if (!ErrMsg.empty()) {
1864 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001865 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001866 I != E; ++I) {
1867 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001868 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001869 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001870 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001871
Daniel Dunbar32141c82010-02-23 20:23:45 +00001872 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001873 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001874
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001875 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001876 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001877 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001878 RemappedFiles.size(),
1879 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001880 if (ATU) {
1881 LoadSerializedDiagnostics(DiagnosticsFile,
1882 num_unsaved_files, unsaved_files,
1883 ATU->getFileManager(),
1884 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001885 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001886 } else if (CXXIdx->getDisplayDiagnostics()) {
1887 // We failed to load the ASTUnit, but we can still deserialize the
1888 // diagnostics and emit them.
1889 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001890 Diagnostic Diag;
1891 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001892 // FIXME: Faked LangOpts!
1893 LangOptions LangOpts;
1894 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1895 LoadSerializedDiagnostics(DiagnosticsFile,
1896 num_unsaved_files, unsaved_files,
1897 FileMgr, SourceMgr, Diags);
1898 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1899 DEnd = Diags.end();
1900 D != DEnd; ++D) {
1901 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001902 CXString Msg = clang_formatDiagnostic(&Diag,
1903 clang_defaultDiagnosticDisplayOptions());
1904 fprintf(stderr, "%s\n", clang_getCString(Msg));
1905 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001906 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001907
1908#ifdef LLVM_ON_WIN32
1909 // On Windows, force a flush, since there may be multiple copies of
1910 // stderr and stdout in the file system, all with different buffers
1911 // but writing to the same device.
1912 fflush(stderr);
1913#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001914 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001915
Douglas Gregor313e26c2010-02-18 23:35:40 +00001916 if (ATU) {
1917 // Make the translation unit responsible for destroying all temporary files.
1918 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1919 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001920 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001921 } else {
1922 // Destroy all of the temporary files now; they can't be referenced any
1923 // longer.
1924 llvm::sys::Path(astTmpFile).eraseFromDisk();
1925 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1926 TemporaryFiles[i].eraseFromDisk();
1927 }
1928
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001929 PTUI->result = ATU;
1930}
1931CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1932 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001933 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001934 int num_command_line_args,
1935 struct CXUnsavedFile *unsaved_files,
1936 unsigned num_unsaved_files,
1937 unsigned options) {
1938 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1939 num_command_line_args, unsaved_files, num_unsaved_files,
1940 options, 0 };
1941 llvm::CrashRecoveryContext CRC;
1942
1943 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001944 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1945 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1946 fprintf(stderr, " 'command_line_args' : [");
1947 for (int i = 0; i != num_command_line_args; ++i) {
1948 if (i)
1949 fprintf(stderr, ", ");
1950 fprintf(stderr, "'%s'", command_line_args[i]);
1951 }
1952 fprintf(stderr, "],\n");
1953 fprintf(stderr, " 'unsaved_files' : [");
1954 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1955 if (i)
1956 fprintf(stderr, ", ");
1957 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1958 unsaved_files[i].Length);
1959 }
1960 fprintf(stderr, "],\n");
1961 fprintf(stderr, " 'options' : %d,\n", options);
1962 fprintf(stderr, "}\n");
1963
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001964 return 0;
1965 }
1966
1967 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001968}
1969
Douglas Gregor19998442010-08-13 15:35:05 +00001970unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1971 return CXSaveTranslationUnit_None;
1972}
1973
1974int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1975 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001976 if (!TU)
1977 return 1;
1978
1979 return static_cast<ASTUnit *>(TU)->Save(FileName);
1980}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001981
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001982void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001983 if (CTUnit) {
1984 // If the translation unit has been marked as unsafe to free, just discard
1985 // it.
1986 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1987 return;
1988
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001989 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001990 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001991}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001992
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001993unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1994 return CXReparse_None;
1995}
1996
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001997struct ReparseTranslationUnitInfo {
1998 CXTranslationUnit TU;
1999 unsigned num_unsaved_files;
2000 struct CXUnsavedFile *unsaved_files;
2001 unsigned options;
2002 int result;
2003};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002004static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002005 ReparseTranslationUnitInfo *RTUI =
2006 static_cast<ReparseTranslationUnitInfo*>(UserData);
2007 CXTranslationUnit TU = RTUI->TU;
2008 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2009 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2010 unsigned options = RTUI->options;
2011 (void) options;
2012 RTUI->result = 1;
2013
Douglas Gregorabc563f2010-07-19 21:46:24 +00002014 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002015 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002016
2017 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2018 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2019 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2020 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002021 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002022 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2023 Buffer));
2024 }
2025
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002026 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
2027 RemappedFiles.size()))
2028 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002029}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002030int clang_reparseTranslationUnit(CXTranslationUnit TU,
2031 unsigned num_unsaved_files,
2032 struct CXUnsavedFile *unsaved_files,
2033 unsigned options) {
2034 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2035 options, 0 };
2036 llvm::CrashRecoveryContext CRC;
2037
2038 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002039 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002040 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2041 return 1;
2042 }
2043
2044 return RTUI.result;
2045}
2046
Douglas Gregordf95a132010-08-09 20:45:32 +00002047
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002048CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002049 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002050 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002051
Steve Naroff77accc12009-09-03 18:19:54 +00002052 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002053 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002054}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002055
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002056CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002057 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002058 return Result;
2059}
2060
Ted Kremenekfb480492010-01-13 21:46:36 +00002061} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002062
Ted Kremenekfb480492010-01-13 21:46:36 +00002063//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002064// CXSourceLocation and CXSourceRange Operations.
2065//===----------------------------------------------------------------------===//
2066
Douglas Gregorb9790342010-01-22 21:44:22 +00002067extern "C" {
2068CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002069 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002070 return Result;
2071}
2072
2073unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002074 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2075 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2076 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002077}
2078
2079CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2080 CXFile file,
2081 unsigned line,
2082 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002083 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002084 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002085
Douglas Gregorb9790342010-01-22 21:44:22 +00002086 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2087 SourceLocation SLoc
2088 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002089 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002090 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002091
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002092 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002093}
2094
Douglas Gregor5352ac02010-01-28 00:27:43 +00002095CXSourceRange clang_getNullRange() {
2096 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2097 return Result;
2098}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002099
Douglas Gregor5352ac02010-01-28 00:27:43 +00002100CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2101 if (begin.ptr_data[0] != end.ptr_data[0] ||
2102 begin.ptr_data[1] != end.ptr_data[1])
2103 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002104
2105 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002106 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002107 return Result;
2108}
2109
Douglas Gregor46766dc2010-01-26 19:19:08 +00002110void clang_getInstantiationLocation(CXSourceLocation location,
2111 CXFile *file,
2112 unsigned *line,
2113 unsigned *column,
2114 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002115 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2116
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002117 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002118 if (file)
2119 *file = 0;
2120 if (line)
2121 *line = 0;
2122 if (column)
2123 *column = 0;
2124 if (offset)
2125 *offset = 0;
2126 return;
2127 }
2128
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002129 const SourceManager &SM =
2130 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002131 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002132
2133 if (file)
2134 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2135 if (line)
2136 *line = SM.getInstantiationLineNumber(InstLoc);
2137 if (column)
2138 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002139 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002140 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002141}
2142
Douglas Gregor1db19de2010-01-19 21:36:55 +00002143CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002144 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002145 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002146 return Result;
2147}
2148
2149CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002150 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002151 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002152 return Result;
2153}
2154
Douglas Gregorb9790342010-01-22 21:44:22 +00002155} // end: extern "C"
2156
Douglas Gregor1db19de2010-01-19 21:36:55 +00002157//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002158// CXFile Operations.
2159//===----------------------------------------------------------------------===//
2160
2161extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002162CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002163 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002164 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002165
Steve Naroff88145032009-10-27 14:35:18 +00002166 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002167 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002168}
2169
2170time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002171 if (!SFile)
2172 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002173
Steve Naroff88145032009-10-27 14:35:18 +00002174 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2175 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002176}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002177
Douglas Gregorb9790342010-01-22 21:44:22 +00002178CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2179 if (!tu)
2180 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002181
Douglas Gregorb9790342010-01-22 21:44:22 +00002182 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002183
Douglas Gregorb9790342010-01-22 21:44:22 +00002184 FileManager &FMgr = CXXUnit->getFileManager();
2185 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2186 return const_cast<FileEntry *>(File);
2187}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002188
Ted Kremenekfb480492010-01-13 21:46:36 +00002189} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002190
Ted Kremenekfb480492010-01-13 21:46:36 +00002191//===----------------------------------------------------------------------===//
2192// CXCursor Operations.
2193//===----------------------------------------------------------------------===//
2194
Ted Kremenekfb480492010-01-13 21:46:36 +00002195static Decl *getDeclFromExpr(Stmt *E) {
2196 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2197 return RefExpr->getDecl();
2198 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2199 return ME->getMemberDecl();
2200 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2201 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002202
Ted Kremenekfb480492010-01-13 21:46:36 +00002203 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2204 return getDeclFromExpr(CE->getCallee());
2205 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2206 return getDeclFromExpr(CE->getSubExpr());
2207 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2208 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002209
Ted Kremenekfb480492010-01-13 21:46:36 +00002210 return 0;
2211}
2212
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002213static SourceLocation getLocationFromExpr(Expr *E) {
2214 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2215 return /*FIXME:*/Msg->getLeftLoc();
2216 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2217 return DRE->getLocation();
2218 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2219 return Member->getMemberLoc();
2220 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2221 return Ivar->getLocation();
2222 return E->getLocStart();
2223}
2224
Ted Kremenekfb480492010-01-13 21:46:36 +00002225extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002226
2227unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002228 CXCursorVisitor visitor,
2229 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002230 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002231
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002232 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2233 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002234 return CursorVis.VisitChildren(parent);
2235}
2236
Douglas Gregor78205d42010-01-20 21:45:58 +00002237static CXString getDeclSpelling(Decl *D) {
2238 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2239 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002240 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002241
Douglas Gregor78205d42010-01-20 21:45:58 +00002242 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002243 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002244
Douglas Gregor78205d42010-01-20 21:45:58 +00002245 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2246 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2247 // and returns different names. NamedDecl returns the class name and
2248 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002249 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002250
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002251 if (isa<UsingDirectiveDecl>(D))
2252 return createCXString("");
2253
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002254 llvm::SmallString<1024> S;
2255 llvm::raw_svector_ostream os(S);
2256 ND->printName(os);
2257
2258 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002259}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002260
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002261CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002262 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002263 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002264
Steve Narofff334b4e2009-09-02 18:26:48 +00002265 if (clang_isReference(C.kind)) {
2266 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002267 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002268 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002269 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002270 }
2271 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002272 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002273 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002274 }
2275 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002276 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002277 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002278 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002279 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002280 case CXCursor_CXXBaseSpecifier: {
2281 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2282 return createCXString(B->getType().getAsString());
2283 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002284 case CXCursor_TypeRef: {
2285 TypeDecl *Type = getCursorTypeRef(C).first;
2286 assert(Type && "Missing type decl");
2287
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002288 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2289 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002290 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002291 case CXCursor_TemplateRef: {
2292 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002293 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002294
2295 return createCXString(Template->getNameAsString());
2296 }
Douglas Gregor69319002010-08-31 23:48:11 +00002297
2298 case CXCursor_NamespaceRef: {
2299 NamedDecl *NS = getCursorNamespaceRef(C).first;
2300 assert(NS && "Missing namespace decl");
2301
2302 return createCXString(NS->getNameAsString());
2303 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002304
Daniel Dunbaracca7252009-11-30 20:42:49 +00002305 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002306 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002307 }
2308 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002309
2310 if (clang_isExpression(C.kind)) {
2311 Decl *D = getDeclFromExpr(getCursorExpr(C));
2312 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002313 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002314 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002315 }
2316
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002317 if (C.kind == CXCursor_MacroInstantiation)
2318 return createCXString(getCursorMacroInstantiation(C)->getName()
2319 ->getNameStart());
2320
Douglas Gregor572feb22010-03-18 18:04:21 +00002321 if (C.kind == CXCursor_MacroDefinition)
2322 return createCXString(getCursorMacroDefinition(C)->getName()
2323 ->getNameStart());
2324
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002325 if (clang_isDeclaration(C.kind))
2326 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002327
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002328 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002329}
2330
Ted Kremeneke68fff62010-02-17 00:41:32 +00002331CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002332 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002333 case CXCursor_FunctionDecl:
2334 return createCXString("FunctionDecl");
2335 case CXCursor_TypedefDecl:
2336 return createCXString("TypedefDecl");
2337 case CXCursor_EnumDecl:
2338 return createCXString("EnumDecl");
2339 case CXCursor_EnumConstantDecl:
2340 return createCXString("EnumConstantDecl");
2341 case CXCursor_StructDecl:
2342 return createCXString("StructDecl");
2343 case CXCursor_UnionDecl:
2344 return createCXString("UnionDecl");
2345 case CXCursor_ClassDecl:
2346 return createCXString("ClassDecl");
2347 case CXCursor_FieldDecl:
2348 return createCXString("FieldDecl");
2349 case CXCursor_VarDecl:
2350 return createCXString("VarDecl");
2351 case CXCursor_ParmDecl:
2352 return createCXString("ParmDecl");
2353 case CXCursor_ObjCInterfaceDecl:
2354 return createCXString("ObjCInterfaceDecl");
2355 case CXCursor_ObjCCategoryDecl:
2356 return createCXString("ObjCCategoryDecl");
2357 case CXCursor_ObjCProtocolDecl:
2358 return createCXString("ObjCProtocolDecl");
2359 case CXCursor_ObjCPropertyDecl:
2360 return createCXString("ObjCPropertyDecl");
2361 case CXCursor_ObjCIvarDecl:
2362 return createCXString("ObjCIvarDecl");
2363 case CXCursor_ObjCInstanceMethodDecl:
2364 return createCXString("ObjCInstanceMethodDecl");
2365 case CXCursor_ObjCClassMethodDecl:
2366 return createCXString("ObjCClassMethodDecl");
2367 case CXCursor_ObjCImplementationDecl:
2368 return createCXString("ObjCImplementationDecl");
2369 case CXCursor_ObjCCategoryImplDecl:
2370 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002371 case CXCursor_CXXMethod:
2372 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002373 case CXCursor_UnexposedDecl:
2374 return createCXString("UnexposedDecl");
2375 case CXCursor_ObjCSuperClassRef:
2376 return createCXString("ObjCSuperClassRef");
2377 case CXCursor_ObjCProtocolRef:
2378 return createCXString("ObjCProtocolRef");
2379 case CXCursor_ObjCClassRef:
2380 return createCXString("ObjCClassRef");
2381 case CXCursor_TypeRef:
2382 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002383 case CXCursor_TemplateRef:
2384 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002385 case CXCursor_NamespaceRef:
2386 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002387 case CXCursor_UnexposedExpr:
2388 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002389 case CXCursor_BlockExpr:
2390 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002391 case CXCursor_DeclRefExpr:
2392 return createCXString("DeclRefExpr");
2393 case CXCursor_MemberRefExpr:
2394 return createCXString("MemberRefExpr");
2395 case CXCursor_CallExpr:
2396 return createCXString("CallExpr");
2397 case CXCursor_ObjCMessageExpr:
2398 return createCXString("ObjCMessageExpr");
2399 case CXCursor_UnexposedStmt:
2400 return createCXString("UnexposedStmt");
2401 case CXCursor_InvalidFile:
2402 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002403 case CXCursor_InvalidCode:
2404 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002405 case CXCursor_NoDeclFound:
2406 return createCXString("NoDeclFound");
2407 case CXCursor_NotImplemented:
2408 return createCXString("NotImplemented");
2409 case CXCursor_TranslationUnit:
2410 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002411 case CXCursor_UnexposedAttr:
2412 return createCXString("UnexposedAttr");
2413 case CXCursor_IBActionAttr:
2414 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002415 case CXCursor_IBOutletAttr:
2416 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002417 case CXCursor_IBOutletCollectionAttr:
2418 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002419 case CXCursor_PreprocessingDirective:
2420 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002421 case CXCursor_MacroDefinition:
2422 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002423 case CXCursor_MacroInstantiation:
2424 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002425 case CXCursor_Namespace:
2426 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002427 case CXCursor_LinkageSpec:
2428 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002429 case CXCursor_CXXBaseSpecifier:
2430 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002431 case CXCursor_Constructor:
2432 return createCXString("CXXConstructor");
2433 case CXCursor_Destructor:
2434 return createCXString("CXXDestructor");
2435 case CXCursor_ConversionFunction:
2436 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002437 case CXCursor_TemplateTypeParameter:
2438 return createCXString("TemplateTypeParameter");
2439 case CXCursor_NonTypeTemplateParameter:
2440 return createCXString("NonTypeTemplateParameter");
2441 case CXCursor_TemplateTemplateParameter:
2442 return createCXString("TemplateTemplateParameter");
2443 case CXCursor_FunctionTemplate:
2444 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002445 case CXCursor_ClassTemplate:
2446 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002447 case CXCursor_ClassTemplatePartialSpecialization:
2448 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002449 case CXCursor_NamespaceAlias:
2450 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002451 case CXCursor_UsingDirective:
2452 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002453 case CXCursor_UsingDeclaration:
2454 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002455 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002456
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002457 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002458 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002459}
Steve Naroff89922f82009-08-31 00:59:03 +00002460
Ted Kremeneke68fff62010-02-17 00:41:32 +00002461enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2462 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002463 CXClientData client_data) {
2464 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2465 *BestCursor = cursor;
2466 return CXChildVisit_Recurse;
2467}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002468
Douglas Gregorb9790342010-01-22 21:44:22 +00002469CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2470 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002471 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002472
Douglas Gregorb9790342010-01-22 21:44:22 +00002473 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002474 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2475
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002476 // Translate the given source location to make it point at the beginning of
2477 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002478 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002479
2480 // Guard against an invalid SourceLocation, or we may assert in one
2481 // of the following calls.
2482 if (SLoc.isInvalid())
2483 return clang_getNullCursor();
2484
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002485 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2486 CXXUnit->getASTContext().getLangOptions());
2487
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002488 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2489 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002490 // FIXME: Would be great to have a "hint" cursor, then walk from that
2491 // hint cursor upward until we find a cursor whose source range encloses
2492 // the region of interest, rather than starting from the translation unit.
2493 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002494 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002495 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002496 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002497 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002498 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002499}
2500
Ted Kremenek73885552009-11-17 19:28:59 +00002501CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002502 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002503}
2504
2505unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002506 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002507}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002508
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002509unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002510 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2511}
2512
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002513unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002514 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2515}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002516
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002517unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002518 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2519}
2520
Douglas Gregor97b98722010-01-19 23:20:36 +00002521unsigned clang_isExpression(enum CXCursorKind K) {
2522 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2523}
2524
2525unsigned clang_isStatement(enum CXCursorKind K) {
2526 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2527}
2528
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002529unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2530 return K == CXCursor_TranslationUnit;
2531}
2532
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002533unsigned clang_isPreprocessing(enum CXCursorKind K) {
2534 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2535}
2536
Ted Kremenekad6eff62010-03-08 21:17:29 +00002537unsigned clang_isUnexposed(enum CXCursorKind K) {
2538 switch (K) {
2539 case CXCursor_UnexposedDecl:
2540 case CXCursor_UnexposedExpr:
2541 case CXCursor_UnexposedStmt:
2542 case CXCursor_UnexposedAttr:
2543 return true;
2544 default:
2545 return false;
2546 }
2547}
2548
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002549CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002550 return C.kind;
2551}
2552
Douglas Gregor98258af2010-01-18 22:46:11 +00002553CXSourceLocation clang_getCursorLocation(CXCursor C) {
2554 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002555 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002556 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002557 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2558 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002559 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002560 }
2561
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002562 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002563 std::pair<ObjCProtocolDecl *, SourceLocation> P
2564 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002565 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002566 }
2567
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002568 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002569 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2570 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002571 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002572 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002573
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002574 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002575 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002576 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002577 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002578
2579 case CXCursor_TemplateRef: {
2580 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2581 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2582 }
2583
Douglas Gregor69319002010-08-31 23:48:11 +00002584 case CXCursor_NamespaceRef: {
2585 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2586 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2587 }
2588
Ted Kremenek3064ef92010-08-27 21:34:58 +00002589 case CXCursor_CXXBaseSpecifier: {
2590 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2591 return clang_getNullLocation();
2592 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002593
Douglas Gregorf46034a2010-01-18 23:41:10 +00002594 default:
2595 // FIXME: Need a way to enumerate all non-reference cases.
2596 llvm_unreachable("Missed a reference kind");
2597 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002598 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002599
2600 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002601 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002602 getLocationFromExpr(getCursorExpr(C)));
2603
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002604 if (C.kind == CXCursor_PreprocessingDirective) {
2605 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2606 return cxloc::translateSourceLocation(getCursorContext(C), L);
2607 }
Douglas Gregor48072312010-03-18 15:23:44 +00002608
2609 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002610 SourceLocation L
2611 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002612 return cxloc::translateSourceLocation(getCursorContext(C), L);
2613 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002614
2615 if (C.kind == CXCursor_MacroDefinition) {
2616 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2617 return cxloc::translateSourceLocation(getCursorContext(C), L);
2618 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002619
Ted Kremenek9a700d22010-05-12 06:16:13 +00002620 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002621 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002622
Douglas Gregorf46034a2010-01-18 23:41:10 +00002623 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002624 SourceLocation Loc = D->getLocation();
2625 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2626 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002627 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002628}
Douglas Gregora7bde202010-01-19 00:34:46 +00002629
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002630} // end extern "C"
2631
2632static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002633 if (clang_isReference(C.kind)) {
2634 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002635 case CXCursor_ObjCSuperClassRef:
2636 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002637
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002638 case CXCursor_ObjCProtocolRef:
2639 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002640
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002641 case CXCursor_ObjCClassRef:
2642 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002643
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002644 case CXCursor_TypeRef:
2645 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002646
2647 case CXCursor_TemplateRef:
2648 return getCursorTemplateRef(C).second;
2649
Douglas Gregor69319002010-08-31 23:48:11 +00002650 case CXCursor_NamespaceRef:
2651 return getCursorNamespaceRef(C).second;
2652
Ted Kremenek3064ef92010-08-27 21:34:58 +00002653 case CXCursor_CXXBaseSpecifier:
2654 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2655 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002656
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002657 default:
2658 // FIXME: Need a way to enumerate all non-reference cases.
2659 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002660 }
2661 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002662
2663 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002664 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002665
2666 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002667 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002668
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002669 if (C.kind == CXCursor_PreprocessingDirective)
2670 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002671
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002672 if (C.kind == CXCursor_MacroInstantiation)
2673 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002674
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002675 if (C.kind == CXCursor_MacroDefinition)
2676 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002677
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002678 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2679 return getCursorDecl(C)->getSourceRange();
2680
2681 return SourceRange();
2682}
2683
2684extern "C" {
2685
2686CXSourceRange clang_getCursorExtent(CXCursor C) {
2687 SourceRange R = getRawCursorExtent(C);
2688 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002689 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002690
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002691 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002692}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002693
2694CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002695 if (clang_isInvalid(C.kind))
2696 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002697
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002698 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002699 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002700 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002701
Douglas Gregor97b98722010-01-19 23:20:36 +00002702 if (clang_isExpression(C.kind)) {
2703 Decl *D = getDeclFromExpr(getCursorExpr(C));
2704 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002705 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002706 return clang_getNullCursor();
2707 }
2708
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002709 if (C.kind == CXCursor_MacroInstantiation) {
2710 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2711 return MakeMacroDefinitionCursor(Def, CXXUnit);
2712 }
2713
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002714 if (!clang_isReference(C.kind))
2715 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002716
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002717 switch (C.kind) {
2718 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002719 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002720
2721 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002722 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002723
2724 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002725 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002726
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002727 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002728 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002729
2730 case CXCursor_TemplateRef:
2731 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2732
Douglas Gregor69319002010-08-31 23:48:11 +00002733 case CXCursor_NamespaceRef:
2734 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2735
Ted Kremenek3064ef92010-08-27 21:34:58 +00002736 case CXCursor_CXXBaseSpecifier: {
2737 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2738 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2739 CXXUnit));
2740 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002741
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002742 default:
2743 // We would prefer to enumerate all non-reference cursor kinds here.
2744 llvm_unreachable("Unhandled reference cursor kind");
2745 break;
2746 }
2747 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002748
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002749 return clang_getNullCursor();
2750}
2751
Douglas Gregorb6998662010-01-19 19:34:47 +00002752CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002753 if (clang_isInvalid(C.kind))
2754 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002755
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002756 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002757
Douglas Gregorb6998662010-01-19 19:34:47 +00002758 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002759 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002760 C = clang_getCursorReferenced(C);
2761 WasReference = true;
2762 }
2763
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002764 if (C.kind == CXCursor_MacroInstantiation)
2765 return clang_getCursorReferenced(C);
2766
Douglas Gregorb6998662010-01-19 19:34:47 +00002767 if (!clang_isDeclaration(C.kind))
2768 return clang_getNullCursor();
2769
2770 Decl *D = getCursorDecl(C);
2771 if (!D)
2772 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002773
Douglas Gregorb6998662010-01-19 19:34:47 +00002774 switch (D->getKind()) {
2775 // Declaration kinds that don't really separate the notions of
2776 // declaration and definition.
2777 case Decl::Namespace:
2778 case Decl::Typedef:
2779 case Decl::TemplateTypeParm:
2780 case Decl::EnumConstant:
2781 case Decl::Field:
2782 case Decl::ObjCIvar:
2783 case Decl::ObjCAtDefsField:
2784 case Decl::ImplicitParam:
2785 case Decl::ParmVar:
2786 case Decl::NonTypeTemplateParm:
2787 case Decl::TemplateTemplateParm:
2788 case Decl::ObjCCategoryImpl:
2789 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002790 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002791 case Decl::LinkageSpec:
2792 case Decl::ObjCPropertyImpl:
2793 case Decl::FileScopeAsm:
2794 case Decl::StaticAssert:
2795 case Decl::Block:
2796 return C;
2797
2798 // Declaration kinds that don't make any sense here, but are
2799 // nonetheless harmless.
2800 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002801 break;
2802
2803 // Declaration kinds for which the definition is not resolvable.
2804 case Decl::UnresolvedUsingTypename:
2805 case Decl::UnresolvedUsingValue:
2806 break;
2807
2808 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002809 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2810 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002811
2812 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002813 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002814
2815 case Decl::Enum:
2816 case Decl::Record:
2817 case Decl::CXXRecord:
2818 case Decl::ClassTemplateSpecialization:
2819 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002820 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002821 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002822 return clang_getNullCursor();
2823
2824 case Decl::Function:
2825 case Decl::CXXMethod:
2826 case Decl::CXXConstructor:
2827 case Decl::CXXDestructor:
2828 case Decl::CXXConversion: {
2829 const FunctionDecl *Def = 0;
2830 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002831 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002832 return clang_getNullCursor();
2833 }
2834
2835 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002836 // Ask the variable if it has a definition.
2837 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2838 return MakeCXCursor(Def, CXXUnit);
2839 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002840 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002841
Douglas Gregorb6998662010-01-19 19:34:47 +00002842 case Decl::FunctionTemplate: {
2843 const FunctionDecl *Def = 0;
2844 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002845 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002846 return clang_getNullCursor();
2847 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002848
Douglas Gregorb6998662010-01-19 19:34:47 +00002849 case Decl::ClassTemplate: {
2850 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002851 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002852 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002853 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002854 return clang_getNullCursor();
2855 }
2856
2857 case Decl::Using: {
2858 UsingDecl *Using = cast<UsingDecl>(D);
2859 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002860 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2861 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002862 S != SEnd; ++S) {
2863 if (Def != clang_getNullCursor()) {
2864 // FIXME: We have no way to return multiple results.
2865 return clang_getNullCursor();
2866 }
2867
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002868 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002869 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002870 }
2871
2872 return Def;
2873 }
2874
2875 case Decl::UsingShadow:
2876 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002877 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002878 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002879
2880 case Decl::ObjCMethod: {
2881 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2882 if (Method->isThisDeclarationADefinition())
2883 return C;
2884
2885 // Dig out the method definition in the associated
2886 // @implementation, if we have it.
2887 // FIXME: The ASTs should make finding the definition easier.
2888 if (ObjCInterfaceDecl *Class
2889 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2890 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2891 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2892 Method->isInstanceMethod()))
2893 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002894 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002895
2896 return clang_getNullCursor();
2897 }
2898
2899 case Decl::ObjCCategory:
2900 if (ObjCCategoryImplDecl *Impl
2901 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002902 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002903 return clang_getNullCursor();
2904
2905 case Decl::ObjCProtocol:
2906 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2907 return C;
2908 return clang_getNullCursor();
2909
2910 case Decl::ObjCInterface:
2911 // There are two notions of a "definition" for an Objective-C
2912 // class: the interface and its implementation. When we resolved a
2913 // reference to an Objective-C class, produce the @interface as
2914 // the definition; when we were provided with the interface,
2915 // produce the @implementation as the definition.
2916 if (WasReference) {
2917 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2918 return C;
2919 } else if (ObjCImplementationDecl *Impl
2920 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002921 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002922 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002923
Douglas Gregorb6998662010-01-19 19:34:47 +00002924 case Decl::ObjCProperty:
2925 // FIXME: We don't really know where to find the
2926 // ObjCPropertyImplDecls that implement this property.
2927 return clang_getNullCursor();
2928
2929 case Decl::ObjCCompatibleAlias:
2930 if (ObjCInterfaceDecl *Class
2931 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2932 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002933 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002934
Douglas Gregorb6998662010-01-19 19:34:47 +00002935 return clang_getNullCursor();
2936
2937 case Decl::ObjCForwardProtocol: {
2938 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2939 if (Forward->protocol_size() == 1)
2940 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002941 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002942 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002943
2944 // FIXME: Cannot return multiple definitions.
2945 return clang_getNullCursor();
2946 }
2947
2948 case Decl::ObjCClass: {
2949 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2950 if (Class->size() == 1) {
2951 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2952 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002953 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002954 return clang_getNullCursor();
2955 }
2956
2957 // FIXME: Cannot return multiple definitions.
2958 return clang_getNullCursor();
2959 }
2960
2961 case Decl::Friend:
2962 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002963 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002964 return clang_getNullCursor();
2965
2966 case Decl::FriendTemplate:
2967 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002968 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002969 return clang_getNullCursor();
2970 }
2971
2972 return clang_getNullCursor();
2973}
2974
2975unsigned clang_isCursorDefinition(CXCursor C) {
2976 if (!clang_isDeclaration(C.kind))
2977 return 0;
2978
2979 return clang_getCursorDefinition(C) == C;
2980}
2981
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002982void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002983 const char **startBuf,
2984 const char **endBuf,
2985 unsigned *startLine,
2986 unsigned *startColumn,
2987 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002988 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002989 assert(getCursorDecl(C) && "CXCursor has null decl");
2990 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002991 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2992 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002993
Steve Naroff4ade6d62009-09-23 17:52:52 +00002994 SourceManager &SM = FD->getASTContext().getSourceManager();
2995 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2996 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2997 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2998 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2999 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3000 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3001}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003002
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003003void clang_enableStackTraces(void) {
3004 llvm::sys::PrintStackTraceOnErrorSignal();
3005}
3006
Ted Kremenekfb480492010-01-13 21:46:36 +00003007} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003008
Ted Kremenekfb480492010-01-13 21:46:36 +00003009//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003010// Token-based Operations.
3011//===----------------------------------------------------------------------===//
3012
3013/* CXToken layout:
3014 * int_data[0]: a CXTokenKind
3015 * int_data[1]: starting token location
3016 * int_data[2]: token length
3017 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003018 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003019 * otherwise unused.
3020 */
3021extern "C" {
3022
3023CXTokenKind clang_getTokenKind(CXToken CXTok) {
3024 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3025}
3026
3027CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3028 switch (clang_getTokenKind(CXTok)) {
3029 case CXToken_Identifier:
3030 case CXToken_Keyword:
3031 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003032 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3033 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003034
3035 case CXToken_Literal: {
3036 // We have stashed the starting pointer in the ptr_data field. Use it.
3037 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003038 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003039 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003040
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003041 case CXToken_Punctuation:
3042 case CXToken_Comment:
3043 break;
3044 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003045
3046 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003047 // deconstructing the source location.
3048 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3049 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003050 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003051
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003052 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3053 std::pair<FileID, unsigned> LocInfo
3054 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003055 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003056 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003057 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3058 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003059 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003060
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003061 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003062}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003063
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003064CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3065 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3066 if (!CXXUnit)
3067 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003068
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003069 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3070 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3071}
3072
3073CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3074 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003075 if (!CXXUnit)
3076 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003077
3078 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003079 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3080}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003081
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003082void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3083 CXToken **Tokens, unsigned *NumTokens) {
3084 if (Tokens)
3085 *Tokens = 0;
3086 if (NumTokens)
3087 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003088
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003089 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3090 if (!CXXUnit || !Tokens || !NumTokens)
3091 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003092
Douglas Gregorbdf60622010-03-05 21:16:25 +00003093 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3094
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003095 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003096 if (R.isInvalid())
3097 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003098
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003099 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3100 std::pair<FileID, unsigned> BeginLocInfo
3101 = SourceMgr.getDecomposedLoc(R.getBegin());
3102 std::pair<FileID, unsigned> EndLocInfo
3103 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003104
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003105 // Cannot tokenize across files.
3106 if (BeginLocInfo.first != EndLocInfo.first)
3107 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003108
3109 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003110 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003111 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003112 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003113 if (Invalid)
3114 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003115
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003116 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3117 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003118 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003119 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003120
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003121 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003122 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003123 llvm::SmallVector<CXToken, 32> CXTokens;
3124 Token Tok;
3125 do {
3126 // Lex the next token
3127 Lex.LexFromRawLexer(Tok);
3128 if (Tok.is(tok::eof))
3129 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003130
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003131 // Initialize the CXToken.
3132 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003133
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003134 // - Common fields
3135 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3136 CXTok.int_data[2] = Tok.getLength();
3137 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003138
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003139 // - Kind-specific fields
3140 if (Tok.isLiteral()) {
3141 CXTok.int_data[0] = CXToken_Literal;
3142 CXTok.ptr_data = (void *)Tok.getLiteralData();
3143 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003144 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003145 std::pair<FileID, unsigned> LocInfo
3146 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003147 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003148 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003149 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3150 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003151 return;
3152
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003153 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003154 IdentifierInfo *II
3155 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003156
3157 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3158 CXTok.int_data[0] = CXToken_Keyword;
3159 }
3160 else {
3161 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3162 CXToken_Identifier
3163 : CXToken_Keyword;
3164 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003165 CXTok.ptr_data = II;
3166 } else if (Tok.is(tok::comment)) {
3167 CXTok.int_data[0] = CXToken_Comment;
3168 CXTok.ptr_data = 0;
3169 } else {
3170 CXTok.int_data[0] = CXToken_Punctuation;
3171 CXTok.ptr_data = 0;
3172 }
3173 CXTokens.push_back(CXTok);
3174 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003175
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003176 if (CXTokens.empty())
3177 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003178
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003179 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3180 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3181 *NumTokens = CXTokens.size();
3182}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003183
Ted Kremenek6db61092010-05-05 00:55:15 +00003184void clang_disposeTokens(CXTranslationUnit TU,
3185 CXToken *Tokens, unsigned NumTokens) {
3186 free(Tokens);
3187}
3188
3189} // end: extern "C"
3190
3191//===----------------------------------------------------------------------===//
3192// Token annotation APIs.
3193//===----------------------------------------------------------------------===//
3194
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003195typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003196static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3197 CXCursor parent,
3198 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003199namespace {
3200class AnnotateTokensWorker {
3201 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003202 CXToken *Tokens;
3203 CXCursor *Cursors;
3204 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003205 unsigned TokIdx;
3206 CursorVisitor AnnotateVis;
3207 SourceManager &SrcMgr;
3208
3209 bool MoreTokens() const { return TokIdx < NumTokens; }
3210 unsigned NextToken() const { return TokIdx; }
3211 void AdvanceToken() { ++TokIdx; }
3212 SourceLocation GetTokenLoc(unsigned tokI) {
3213 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3214 }
3215
Ted Kremenek6db61092010-05-05 00:55:15 +00003216public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003217 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003218 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3219 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003220 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003221 NumTokens(numTokens), TokIdx(0),
3222 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3223 Decl::MaxPCHLevel, RegionOfInterest),
3224 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003225
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003226 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003227 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003228 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003229};
3230}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003231
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003232void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3233 // Walk the AST within the region of interest, annotating tokens
3234 // along the way.
3235 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003236
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003237 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3238 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3239 if (Pos != Annotated.end())
3240 Cursors[I] = Pos->second;
3241 }
3242
3243 // Finish up annotating any tokens left.
3244 if (!MoreTokens())
3245 return;
3246
3247 const CXCursor &C = clang_getNullCursor();
3248 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3249 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3250 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003251 }
3252}
3253
Ted Kremenek6db61092010-05-05 00:55:15 +00003254enum CXChildVisitResult
3255AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003256 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3257 // We can always annotate a preprocessing directive/macro instantiation.
3258 if (clang_isPreprocessing(cursor.kind)) {
3259 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003260 return CXChildVisit_Recurse;
3261 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003262
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003263 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003264
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003265 if (cursorRange.isInvalid())
3266 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003267
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003268 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3269
Ted Kremeneka333c662010-05-12 05:29:33 +00003270 // Adjust the annotated range based specific declarations.
3271 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3272 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003273 Decl *D = cxcursor::getCursorDecl(cursor);
3274 // Don't visit synthesized ObjC methods, since they have no syntatic
3275 // representation in the source.
3276 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3277 if (MD->isSynthesized())
3278 return CXChildVisit_Continue;
3279 }
3280 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003281 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3282 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003283 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003284 if (TLoc.isValid() &&
3285 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003286 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003287 }
3288 }
3289 }
3290
Ted Kremenek3f404602010-08-14 01:14:06 +00003291 // If the location of the cursor occurs within a macro instantiation, record
3292 // the spelling location of the cursor in our annotation map. We can then
3293 // paper over the token labelings during a post-processing step to try and
3294 // get cursor mappings for tokens that are the *arguments* of a macro
3295 // instantiation.
3296 if (L.isMacroID()) {
3297 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3298 // Only invalidate the old annotation if it isn't part of a preprocessing
3299 // directive. Here we assume that the default construction of CXCursor
3300 // results in CXCursor.kind being an initialized value (i.e., 0). If
3301 // this isn't the case, we can fix by doing lookup + insertion.
3302
3303 CXCursor &oldC = Annotated[rawEncoding];
3304 if (!clang_isPreprocessing(oldC.kind))
3305 oldC = cursor;
3306 }
3307
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003308 const enum CXCursorKind K = clang_getCursorKind(parent);
3309 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003310 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3311 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003312
3313 while (MoreTokens()) {
3314 const unsigned I = NextToken();
3315 SourceLocation TokLoc = GetTokenLoc(I);
3316 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3317 case RangeBefore:
3318 Cursors[I] = updateC;
3319 AdvanceToken();
3320 continue;
3321 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003322 case RangeOverlap:
3323 break;
3324 }
3325 break;
3326 }
3327
3328 // Visit children to get their cursor information.
3329 const unsigned BeforeChildren = NextToken();
3330 VisitChildren(cursor);
3331 const unsigned AfterChildren = NextToken();
3332
3333 // Adjust 'Last' to the last token within the extent of the cursor.
3334 while (MoreTokens()) {
3335 const unsigned I = NextToken();
3336 SourceLocation TokLoc = GetTokenLoc(I);
3337 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3338 case RangeBefore:
3339 assert(0 && "Infeasible");
3340 case RangeAfter:
3341 break;
3342 case RangeOverlap:
3343 Cursors[I] = updateC;
3344 AdvanceToken();
3345 continue;
3346 }
3347 break;
3348 }
3349 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003350
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003351 // Scan the tokens that are at the beginning of the cursor, but are not
3352 // capture by the child cursors.
3353
3354 // For AST elements within macros, rely on a post-annotate pass to
3355 // to correctly annotate the tokens with cursors. Otherwise we can
3356 // get confusing results of having tokens that map to cursors that really
3357 // are expanded by an instantiation.
3358 if (L.isMacroID())
3359 cursor = clang_getNullCursor();
3360
3361 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3362 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3363 break;
3364 Cursors[I] = cursor;
3365 }
3366 // Scan the tokens that are at the end of the cursor, but are not captured
3367 // but the child cursors.
3368 for (unsigned I = AfterChildren; I != Last; ++I)
3369 Cursors[I] = cursor;
3370
3371 TokIdx = Last;
3372 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003373}
3374
Ted Kremenek6db61092010-05-05 00:55:15 +00003375static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3376 CXCursor parent,
3377 CXClientData client_data) {
3378 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3379}
3380
3381extern "C" {
3382
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003383void clang_annotateTokens(CXTranslationUnit TU,
3384 CXToken *Tokens, unsigned NumTokens,
3385 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003386
3387 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003388 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003389
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003390 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003391 if (!CXXUnit) {
3392 // Any token we don't specifically annotate will have a NULL cursor.
3393 const CXCursor &C = clang_getNullCursor();
3394 for (unsigned I = 0; I != NumTokens; ++I)
3395 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003396 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003397 }
3398
Douglas Gregorbdf60622010-03-05 21:16:25 +00003399 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003400
Douglas Gregor0396f462010-03-19 05:22:59 +00003401 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003402 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003403 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3404 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003405 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3406 clang_getTokenLocation(TU,
3407 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003408
Douglas Gregor0396f462010-03-19 05:22:59 +00003409 // A mapping from the source locations found when re-lexing or traversing the
3410 // region of interest to the corresponding cursors.
3411 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003412
3413 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003414 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003415 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3416 std::pair<FileID, unsigned> BeginLocInfo
3417 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3418 std::pair<FileID, unsigned> EndLocInfo
3419 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003420
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003421 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003422 bool Invalid = false;
3423 if (BeginLocInfo.first == EndLocInfo.first &&
3424 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3425 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003426 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3427 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003428 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003429 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003430 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003431
3432 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003433 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003434 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003435 Token Tok;
3436 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003437
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003438 reprocess:
3439 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3440 // We have found a preprocessing directive. Gobble it up so that we
3441 // don't see it while preprocessing these tokens later, but keep track of
3442 // all of the token locations inside this preprocessing directive so that
3443 // we can annotate them appropriately.
3444 //
3445 // FIXME: Some simple tests here could identify macro definitions and
3446 // #undefs, to provide specific cursor kinds for those.
3447 std::vector<SourceLocation> Locations;
3448 do {
3449 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003450 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003451 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003452
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003453 using namespace cxcursor;
3454 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003455 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3456 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003457 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003458 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3459 Annotated[Locations[I].getRawEncoding()] = Cursor;
3460 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003461
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003462 if (Tok.isAtStartOfLine())
3463 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003464
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003465 continue;
3466 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003467
Douglas Gregor48072312010-03-18 15:23:44 +00003468 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003469 break;
3470 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003471 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003472
Douglas Gregor0396f462010-03-19 05:22:59 +00003473 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003474 // a specific cursor.
3475 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3476 CXXUnit, RegionOfInterest);
3477 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003478}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003479} // end: extern "C"
3480
3481//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003482// Operations for querying linkage of a cursor.
3483//===----------------------------------------------------------------------===//
3484
3485extern "C" {
3486CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003487 if (!clang_isDeclaration(cursor.kind))
3488 return CXLinkage_Invalid;
3489
Ted Kremenek16b42592010-03-03 06:36:57 +00003490 Decl *D = cxcursor::getCursorDecl(cursor);
3491 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3492 switch (ND->getLinkage()) {
3493 case NoLinkage: return CXLinkage_NoLinkage;
3494 case InternalLinkage: return CXLinkage_Internal;
3495 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3496 case ExternalLinkage: return CXLinkage_External;
3497 };
3498
3499 return CXLinkage_Invalid;
3500}
3501} // end: extern "C"
3502
3503//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003504// Operations for querying language of a cursor.
3505//===----------------------------------------------------------------------===//
3506
3507static CXLanguageKind getDeclLanguage(const Decl *D) {
3508 switch (D->getKind()) {
3509 default:
3510 break;
3511 case Decl::ImplicitParam:
3512 case Decl::ObjCAtDefsField:
3513 case Decl::ObjCCategory:
3514 case Decl::ObjCCategoryImpl:
3515 case Decl::ObjCClass:
3516 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003517 case Decl::ObjCForwardProtocol:
3518 case Decl::ObjCImplementation:
3519 case Decl::ObjCInterface:
3520 case Decl::ObjCIvar:
3521 case Decl::ObjCMethod:
3522 case Decl::ObjCProperty:
3523 case Decl::ObjCPropertyImpl:
3524 case Decl::ObjCProtocol:
3525 return CXLanguage_ObjC;
3526 case Decl::CXXConstructor:
3527 case Decl::CXXConversion:
3528 case Decl::CXXDestructor:
3529 case Decl::CXXMethod:
3530 case Decl::CXXRecord:
3531 case Decl::ClassTemplate:
3532 case Decl::ClassTemplatePartialSpecialization:
3533 case Decl::ClassTemplateSpecialization:
3534 case Decl::Friend:
3535 case Decl::FriendTemplate:
3536 case Decl::FunctionTemplate:
3537 case Decl::LinkageSpec:
3538 case Decl::Namespace:
3539 case Decl::NamespaceAlias:
3540 case Decl::NonTypeTemplateParm:
3541 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003542 case Decl::TemplateTemplateParm:
3543 case Decl::TemplateTypeParm:
3544 case Decl::UnresolvedUsingTypename:
3545 case Decl::UnresolvedUsingValue:
3546 case Decl::Using:
3547 case Decl::UsingDirective:
3548 case Decl::UsingShadow:
3549 return CXLanguage_CPlusPlus;
3550 }
3551
3552 return CXLanguage_C;
3553}
3554
3555extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003556
3557enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3558 if (clang_isDeclaration(cursor.kind))
3559 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3560 if (D->hasAttr<UnavailableAttr>() ||
3561 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3562 return CXAvailability_Available;
3563
3564 if (D->hasAttr<DeprecatedAttr>())
3565 return CXAvailability_Deprecated;
3566 }
3567
3568 return CXAvailability_Available;
3569}
3570
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003571CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3572 if (clang_isDeclaration(cursor.kind))
3573 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3574
3575 return CXLanguage_Invalid;
3576}
3577} // end: extern "C"
3578
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003579
3580//===----------------------------------------------------------------------===//
3581// C++ AST instrospection.
3582//===----------------------------------------------------------------------===//
3583
3584extern "C" {
3585unsigned clang_CXXMethod_isStatic(CXCursor C) {
3586 if (!clang_isDeclaration(C.kind))
3587 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003588
3589 CXXMethodDecl *Method = 0;
3590 Decl *D = cxcursor::getCursorDecl(C);
3591 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3592 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3593 else
3594 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3595 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003596}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003597
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003598} // end: extern "C"
3599
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003600//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003601// Attribute introspection.
3602//===----------------------------------------------------------------------===//
3603
3604extern "C" {
3605CXType clang_getIBOutletCollectionType(CXCursor C) {
3606 if (C.kind != CXCursor_IBOutletCollectionAttr)
3607 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3608
3609 IBOutletCollectionAttr *A =
3610 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3611
3612 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3613}
3614} // end: extern "C"
3615
3616//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003617// CXString Operations.
3618//===----------------------------------------------------------------------===//
3619
3620extern "C" {
3621const char *clang_getCString(CXString string) {
3622 return string.Spelling;
3623}
3624
3625void clang_disposeString(CXString string) {
3626 if (string.MustFreeString && string.Spelling)
3627 free((void*)string.Spelling);
3628}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003629
Ted Kremenekfb480492010-01-13 21:46:36 +00003630} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003631
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003632namespace clang { namespace cxstring {
3633CXString createCXString(const char *String, bool DupString){
3634 CXString Str;
3635 if (DupString) {
3636 Str.Spelling = strdup(String);
3637 Str.MustFreeString = 1;
3638 } else {
3639 Str.Spelling = String;
3640 Str.MustFreeString = 0;
3641 }
3642 return Str;
3643}
3644
3645CXString createCXString(llvm::StringRef String, bool DupString) {
3646 CXString Result;
3647 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3648 char *Spelling = (char *)malloc(String.size() + 1);
3649 memmove(Spelling, String.data(), String.size());
3650 Spelling[String.size()] = 0;
3651 Result.Spelling = Spelling;
3652 Result.MustFreeString = 1;
3653 } else {
3654 Result.Spelling = String.data();
3655 Result.MustFreeString = 0;
3656 }
3657 return Result;
3658}
3659}}
3660
Ted Kremenek04bb7162010-01-22 22:44:15 +00003661//===----------------------------------------------------------------------===//
3662// Misc. utility functions.
3663//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003664
Ted Kremenek04bb7162010-01-22 22:44:15 +00003665extern "C" {
3666
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003667CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003668 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003669}
3670
3671} // end: extern "C"