blob: 17afeca4970df3b27f674242277524bcd0769875 [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; }
Douglas Gregor8ab670e2010-09-02 22:19:24 +0000389 // FIXME: CXXTemporaryObjectExpr has poor source-location information.
390 // FIXME: CXXScalarValueInitExpr has poor source-location information.
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000391 // FIXME: CXXNewExpr has poor source-location information
392 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor8ab670e2010-09-02 22:19:24 +0000393 // FIXME: UnaryTypeTraitExpr has poor source-location information.
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000394 bool VisitOverloadExpr(OverloadExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000395};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000396
Ted Kremenekab188932010-01-05 19:32:54 +0000397} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000398
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000399static SourceRange getRawCursorExtent(CXCursor C);
400
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000401RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000402 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
403}
404
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405/// \brief Visit the given cursor and, if requested by the visitor,
406/// its children.
407///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000408/// \param Cursor the cursor to visit.
409///
410/// \param CheckRegionOfInterest if true, then the caller already checked that
411/// this cursor is within the region of interest.
412///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000413/// \returns true if the visitation should be aborted, false if it
414/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000415bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000416 if (clang_isInvalid(Cursor.kind))
417 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000418
Douglas Gregorb1373d02010-01-20 20:59:29 +0000419 if (clang_isDeclaration(Cursor.kind)) {
420 Decl *D = getCursorDecl(Cursor);
421 assert(D && "Invalid declaration cursor");
422 if (D->getPCHLevel() > MaxPCHLevel)
423 return false;
424
425 if (D->isImplicit())
426 return false;
427 }
428
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000429 // If we have a range of interest, and this cursor doesn't intersect with it,
430 // we're done.
431 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000432 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000433 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000434 return false;
435 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000436
Douglas Gregorb1373d02010-01-20 20:59:29 +0000437 switch (Visitor(Cursor, Parent, ClientData)) {
438 case CXChildVisit_Break:
439 return true;
440
441 case CXChildVisit_Continue:
442 return false;
443
444 case CXChildVisit_Recurse:
445 return VisitChildren(Cursor);
446 }
447
Douglas Gregorfd643772010-01-25 16:45:46 +0000448 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000449}
450
Douglas Gregor788f5a12010-03-20 00:41:21 +0000451std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
452CursorVisitor::getPreprocessedEntities() {
453 PreprocessingRecord &PPRec
454 = *TU->getPreprocessor().getPreprocessingRecord();
455
456 bool OnlyLocalDecls
457 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
458
459 // There is no region of interest; we have to walk everything.
460 if (RegionOfInterest.isInvalid())
461 return std::make_pair(PPRec.begin(OnlyLocalDecls),
462 PPRec.end(OnlyLocalDecls));
463
464 // Find the file in which the region of interest lands.
465 SourceManager &SM = TU->getSourceManager();
466 std::pair<FileID, unsigned> Begin
467 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
468 std::pair<FileID, unsigned> End
469 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
470
471 // The region of interest spans files; we have to walk everything.
472 if (Begin.first != End.first)
473 return std::make_pair(PPRec.begin(OnlyLocalDecls),
474 PPRec.end(OnlyLocalDecls));
475
476 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
477 = TU->getPreprocessedEntitiesByFile();
478 if (ByFileMap.empty()) {
479 // Build the mapping from files to sets of preprocessed entities.
480 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
481 EEnd = PPRec.end(OnlyLocalDecls);
482 E != EEnd; ++E) {
483 std::pair<FileID, unsigned> P
484 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
485 ByFileMap[P.first].push_back(*E);
486 }
487 }
488
489 return std::make_pair(ByFileMap[Begin.first].begin(),
490 ByFileMap[Begin.first].end());
491}
492
Douglas Gregorb1373d02010-01-20 20:59:29 +0000493/// \brief Visit the children of the given cursor.
494///
495/// \returns true if the visitation should be aborted, false if it
496/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000497bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000498 if (clang_isReference(Cursor.kind)) {
499 // By definition, references have no children.
500 return false;
501 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000502
503 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000504 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000505 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000506
Douglas Gregorb1373d02010-01-20 20:59:29 +0000507 if (clang_isDeclaration(Cursor.kind)) {
508 Decl *D = getCursorDecl(Cursor);
509 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000510 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000511 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000512
Douglas Gregora59e3902010-01-21 23:27:09 +0000513 if (clang_isStatement(Cursor.kind))
514 return Visit(getCursorStmt(Cursor));
515 if (clang_isExpression(Cursor.kind))
516 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000517
Douglas Gregorb1373d02010-01-20 20:59:29 +0000518 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000519 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000520 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
521 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000522 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
523 TLEnd = CXXUnit->top_level_end();
524 TL != TLEnd; ++TL) {
525 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000526 return true;
527 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000528 } else if (VisitDeclContext(
529 CXXUnit->getASTContext().getTranslationUnitDecl()))
530 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000531
Douglas Gregor0396f462010-03-19 05:22:59 +0000532 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000533 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000534 // FIXME: Once we have the ability to deserialize a preprocessing record,
535 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000536 PreprocessingRecord::iterator E, EEnd;
537 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000538 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
539 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
540 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000541
Douglas Gregor0396f462010-03-19 05:22:59 +0000542 continue;
543 }
544
545 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
546 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
547 return true;
548
549 continue;
550 }
551 }
552 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000553 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000554 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000555
Douglas Gregorb1373d02010-01-20 20:59:29 +0000556 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000557 return false;
558}
559
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000560bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000561 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
562 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000563
Ted Kremenek664cffd2010-07-22 11:30:19 +0000564 if (Stmt *Body = B->getBody())
565 return Visit(MakeCXCursor(Body, StmtParent, TU));
566
567 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000568}
569
Douglas Gregorb1373d02010-01-20 20:59:29 +0000570bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000571 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000572 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000573
Ted Kremenek23173d72010-05-18 21:09:07 +0000574 Decl *D = *I;
575 if (D->getLexicalDeclContext() != DC)
576 continue;
577
578 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000579
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000580 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000581 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000582 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000583 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000584
585 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000586 case RangeBefore:
587 // This declaration comes before the region of interest; skip it.
588 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000589
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000590 case RangeAfter:
591 // This declaration comes after the region of interest; we're done.
592 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000593
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000594 case RangeOverlap:
595 // This declaration overlaps the region of interest; visit it.
596 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000597 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000598 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000599
Daniel Dunbard52864b2010-02-14 10:02:57 +0000600 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000601 return true;
602 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000603
Douglas Gregorb1373d02010-01-20 20:59:29 +0000604 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000605}
606
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000607bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
608 llvm_unreachable("Translation units are visited directly by Visit()");
609 return false;
610}
611
612bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
613 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
614 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000615
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000616 return false;
617}
618
619bool CursorVisitor::VisitTagDecl(TagDecl *D) {
620 return VisitDeclContext(D);
621}
622
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000623bool CursorVisitor::VisitClassTemplateSpecializationDecl(
624 ClassTemplateSpecializationDecl *D) {
625 bool ShouldVisitBody = false;
626 switch (D->getSpecializationKind()) {
627 case TSK_Undeclared:
628 case TSK_ImplicitInstantiation:
629 // Nothing to visit
630 return false;
631
632 case TSK_ExplicitInstantiationDeclaration:
633 case TSK_ExplicitInstantiationDefinition:
634 break;
635
636 case TSK_ExplicitSpecialization:
637 ShouldVisitBody = true;
638 break;
639 }
640
641 // Visit the template arguments used in the specialization.
642 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
643 TypeLoc TL = SpecType->getTypeLoc();
644 if (TemplateSpecializationTypeLoc *TSTLoc
645 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
646 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
647 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
648 return true;
649 }
650 }
651
652 if (ShouldVisitBody && VisitCXXRecordDecl(D))
653 return true;
654
655 return false;
656}
657
Douglas Gregor74dbe642010-08-31 19:31:58 +0000658bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
659 ClassTemplatePartialSpecializationDecl *D) {
660 // FIXME: Visit the "outer" template parameter lists on the TagDecl
661 // before visiting these template parameters.
662 if (VisitTemplateParameters(D->getTemplateParameters()))
663 return true;
664
665 // Visit the partial specialization arguments.
666 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
667 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
668 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
669 return true;
670
671 return VisitCXXRecordDecl(D);
672}
673
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000674bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000675 // Visit the default argument.
676 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
677 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
678 if (Visit(DefArg->getTypeLoc()))
679 return true;
680
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000681 return false;
682}
683
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000684bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
685 if (Expr *Init = D->getInitExpr())
686 return Visit(MakeCXCursor(Init, StmtParent, TU));
687 return false;
688}
689
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000690bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
691 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
692 if (Visit(TSInfo->getTypeLoc()))
693 return true;
694
695 return false;
696}
697
Douglas Gregorb1373d02010-01-20 20:59:29 +0000698bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000699 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
700 // Visit the function declaration's syntactic components in the order
701 // written. This requires a bit of work.
702 TypeLoc TL = TSInfo->getTypeLoc();
703 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
704
705 // If we have a function declared directly (without the use of a typedef),
706 // visit just the return type. Otherwise, just visit the function's type
707 // now.
708 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
709 (!FTL && Visit(TL)))
710 return true;
711
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000712 // Visit the nested-name-specifier, if present.
713 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
714 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
715 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000716
717 // Visit the declaration name.
718 if (VisitDeclarationNameInfo(ND->getNameInfo()))
719 return true;
720
721 // FIXME: Visit explicitly-specified template arguments!
722
723 // Visit the function parameters, if we have a function type.
724 if (FTL && VisitFunctionTypeLoc(*FTL, true))
725 return true;
726
727 // FIXME: Attributes?
728 }
729
Douglas Gregora59e3902010-01-21 23:27:09 +0000730 if (ND->isThisDeclarationADefinition() &&
731 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
732 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000733
Douglas Gregorb1373d02010-01-20 20:59:29 +0000734 return false;
735}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000736
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000737bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
738 if (VisitDeclaratorDecl(D))
739 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000740
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000741 if (Expr *BitWidth = D->getBitWidth())
742 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000743
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000744 return false;
745}
746
747bool CursorVisitor::VisitVarDecl(VarDecl *D) {
748 if (VisitDeclaratorDecl(D))
749 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000750
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000751 if (Expr *Init = D->getInit())
752 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000753
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000754 return false;
755}
756
Douglas Gregor84b51d72010-09-01 20:16:53 +0000757bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
758 if (VisitDeclaratorDecl(D))
759 return true;
760
761 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
762 if (Expr *DefArg = D->getDefaultArgument())
763 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
764
765 return false;
766}
767
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000768bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
769 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
770 // before visiting these template parameters.
771 if (VisitTemplateParameters(D->getTemplateParameters()))
772 return true;
773
774 return VisitFunctionDecl(D->getTemplatedDecl());
775}
776
Douglas Gregor39d6f072010-08-31 19:02:00 +0000777bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
778 // FIXME: Visit the "outer" template parameter lists on the TagDecl
779 // before visiting these template parameters.
780 if (VisitTemplateParameters(D->getTemplateParameters()))
781 return true;
782
783 return VisitCXXRecordDecl(D->getTemplatedDecl());
784}
785
Douglas Gregor84b51d72010-09-01 20:16:53 +0000786bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
787 if (VisitTemplateParameters(D->getTemplateParameters()))
788 return true;
789
790 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
791 VisitTemplateArgumentLoc(D->getDefaultArgument()))
792 return true;
793
794 return false;
795}
796
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000798 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
799 if (Visit(TSInfo->getTypeLoc()))
800 return true;
801
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000802 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000803 PEnd = ND->param_end();
804 P != PEnd; ++P) {
805 if (Visit(MakeCXCursor(*P, TU)))
806 return true;
807 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000808
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000809 if (ND->isThisDeclarationADefinition() &&
810 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
811 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000812
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000813 return false;
814}
815
Douglas Gregora59e3902010-01-21 23:27:09 +0000816bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
817 return VisitDeclContext(D);
818}
819
Douglas Gregorb1373d02010-01-20 20:59:29 +0000820bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000821 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
822 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000823 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000824
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000825 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
826 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
827 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000828 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000829 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000830
Douglas Gregora59e3902010-01-21 23:27:09 +0000831 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000832}
833
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000834bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
835 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
836 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
837 E = PID->protocol_end(); I != E; ++I, ++PL)
838 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
839 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000840
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000841 return VisitObjCContainerDecl(PID);
842}
843
Ted Kremenek23173d72010-05-18 21:09:07 +0000844bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000845 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
846 return true;
847
Ted Kremenek23173d72010-05-18 21:09:07 +0000848 // FIXME: This implements a workaround with @property declarations also being
849 // installed in the DeclContext for the @interface. Eventually this code
850 // should be removed.
851 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
852 if (!CDecl || !CDecl->IsClassExtension())
853 return false;
854
855 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
856 if (!ID)
857 return false;
858
859 IdentifierInfo *PropertyId = PD->getIdentifier();
860 ObjCPropertyDecl *prevDecl =
861 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
862
863 if (!prevDecl)
864 return false;
865
866 // Visit synthesized methods since they will be skipped when visiting
867 // the @interface.
868 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
869 if (MD->isSynthesized())
870 if (Visit(MakeCXCursor(MD, TU)))
871 return true;
872
873 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
874 if (MD->isSynthesized())
875 if (Visit(MakeCXCursor(MD, TU)))
876 return true;
877
878 return false;
879}
880
Douglas Gregorb1373d02010-01-20 20:59:29 +0000881bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000882 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000883 if (D->getSuperClass() &&
884 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000885 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000886 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000887 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000888
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000889 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
890 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
891 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000892 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000893 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000894
Douglas Gregora59e3902010-01-21 23:27:09 +0000895 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000896}
897
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000898bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
899 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000900}
901
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000902bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000903 // 'ID' could be null when dealing with invalid code.
904 if (ObjCInterfaceDecl *ID = D->getClassInterface())
905 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
906 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000907
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000908 return VisitObjCImplDecl(D);
909}
910
911bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
912#if 0
913 // Issue callbacks for super class.
914 // FIXME: No source location information!
915 if (D->getSuperClass() &&
916 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000917 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000918 TU)))
919 return true;
920#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000921
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000922 return VisitObjCImplDecl(D);
923}
924
925bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
926 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
927 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
928 E = D->protocol_end();
929 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000930 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000931 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000932
933 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000934}
935
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000936bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
937 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
938 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
939 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000940
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000941 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000942}
943
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000944bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
945 return VisitDeclContext(D);
946}
947
Douglas Gregor69319002010-08-31 23:48:11 +0000948bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000949 // Visit nested-name-specifier.
950 if (NestedNameSpecifier *Qualifier = D->getQualifier())
951 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
952 return true;
Douglas Gregor69319002010-08-31 23:48:11 +0000953
954 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
955 D->getTargetNameLoc(), TU));
956}
957
Douglas Gregor7e242562010-09-01 19:52:22 +0000958bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000959 // Visit nested-name-specifier.
960 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
961 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
962 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +0000963
964 // FIXME: Provide a multi-reference of some kind for all of the declarations
965 // that the using declaration refers to. We don't have this kind of cursor
966 // yet.
967
968 return VisitDeclarationNameInfo(D->getNameInfo());
969}
970
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000971bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000972 // Visit nested-name-specifier.
973 if (NestedNameSpecifier *Qualifier = D->getQualifier())
974 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
975 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000976
977 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
978 D->getIdentLocation(), TU));
979}
980
Douglas Gregor7e242562010-09-01 19:52:22 +0000981bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000982 // Visit nested-name-specifier.
983 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
984 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
985 return true;
986
Douglas Gregor7e242562010-09-01 19:52:22 +0000987 return VisitDeclarationNameInfo(D->getNameInfo());
988}
989
990bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
991 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000992 // Visit nested-name-specifier.
993 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
994 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
995 return true;
996
Douglas Gregor7e242562010-09-01 19:52:22 +0000997 return false;
998}
999
Douglas Gregor01829d32010-08-31 14:41:23 +00001000bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1001 switch (Name.getName().getNameKind()) {
1002 case clang::DeclarationName::Identifier:
1003 case clang::DeclarationName::CXXLiteralOperatorName:
1004 case clang::DeclarationName::CXXOperatorName:
1005 case clang::DeclarationName::CXXUsingDirective:
1006 return false;
1007
1008 case clang::DeclarationName::CXXConstructorName:
1009 case clang::DeclarationName::CXXDestructorName:
1010 case clang::DeclarationName::CXXConversionFunctionName:
1011 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1012 return Visit(TSInfo->getTypeLoc());
1013 return false;
1014
1015 case clang::DeclarationName::ObjCZeroArgSelector:
1016 case clang::DeclarationName::ObjCOneArgSelector:
1017 case clang::DeclarationName::ObjCMultiArgSelector:
1018 // FIXME: Per-identifier location info?
1019 return false;
1020 }
1021
1022 return false;
1023}
1024
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001025bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1026 SourceRange Range) {
1027 // FIXME: This whole routine is a hack to work around the lack of proper
1028 // source information in nested-name-specifiers (PR5791). Since we do have
1029 // a beginning source location, we can visit the first component of the
1030 // nested-name-specifier, if it's a single-token component.
1031 if (!NNS)
1032 return false;
1033
1034 // Get the first component in the nested-name-specifier.
1035 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1036 NNS = Prefix;
1037
1038 switch (NNS->getKind()) {
1039 case NestedNameSpecifier::Namespace:
1040 // FIXME: The token at this source location might actually have been a
1041 // namespace alias, but we don't model that. Lame!
1042 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1043 TU));
1044
1045 case NestedNameSpecifier::TypeSpec: {
1046 // If the type has a form where we know that the beginning of the source
1047 // range matches up with a reference cursor. Visit the appropriate reference
1048 // cursor.
1049 Type *T = NNS->getAsType();
1050 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1051 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1052 if (const TagType *Tag = dyn_cast<TagType>(T))
1053 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1054 if (const TemplateSpecializationType *TST
1055 = dyn_cast<TemplateSpecializationType>(T))
1056 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1057 break;
1058 }
1059
1060 case NestedNameSpecifier::TypeSpecWithTemplate:
1061 case NestedNameSpecifier::Global:
1062 case NestedNameSpecifier::Identifier:
1063 break;
1064 }
1065
1066 return false;
1067}
1068
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001069bool CursorVisitor::VisitTemplateParameters(
1070 const TemplateParameterList *Params) {
1071 if (!Params)
1072 return false;
1073
1074 for (TemplateParameterList::const_iterator P = Params->begin(),
1075 PEnd = Params->end();
1076 P != PEnd; ++P) {
1077 if (Visit(MakeCXCursor(*P, TU)))
1078 return true;
1079 }
1080
1081 return false;
1082}
1083
Douglas Gregor0b36e612010-08-31 20:37:03 +00001084bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1085 switch (Name.getKind()) {
1086 case TemplateName::Template:
1087 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1088
1089 case TemplateName::OverloadedTemplate:
1090 // FIXME: We need a way to return multiple lookup results in a single
1091 // cursor.
1092 return false;
1093
1094 case TemplateName::DependentTemplate:
1095 // FIXME: Visit nested-name-specifier.
1096 return false;
1097
1098 case TemplateName::QualifiedTemplate:
1099 // FIXME: Visit nested-name-specifier.
1100 return Visit(MakeCursorTemplateRef(
1101 Name.getAsQualifiedTemplateName()->getDecl(),
1102 Loc, TU));
1103 }
1104
1105 return false;
1106}
1107
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001108bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1109 switch (TAL.getArgument().getKind()) {
1110 case TemplateArgument::Null:
1111 case TemplateArgument::Integral:
1112 return false;
1113
1114 case TemplateArgument::Pack:
1115 // FIXME: Implement when variadic templates come along.
1116 return false;
1117
1118 case TemplateArgument::Type:
1119 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1120 return Visit(TSInfo->getTypeLoc());
1121 return false;
1122
1123 case TemplateArgument::Declaration:
1124 if (Expr *E = TAL.getSourceDeclExpression())
1125 return Visit(MakeCXCursor(E, StmtParent, TU));
1126 return false;
1127
1128 case TemplateArgument::Expression:
1129 if (Expr *E = TAL.getSourceExpression())
1130 return Visit(MakeCXCursor(E, StmtParent, TU));
1131 return false;
1132
1133 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001134 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1135 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001136 }
1137
1138 return false;
1139}
1140
Ted Kremeneka0536d82010-05-07 01:04:29 +00001141bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1142 return VisitDeclContext(D);
1143}
1144
Douglas Gregor01829d32010-08-31 14:41:23 +00001145bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1146 return Visit(TL.getUnqualifiedLoc());
1147}
1148
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001149bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1150 ASTContext &Context = TU->getASTContext();
1151
1152 // Some builtin types (such as Objective-C's "id", "sel", and
1153 // "Class") have associated declarations. Create cursors for those.
1154 QualType VisitType;
1155 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001156 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001157 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001158 case BuiltinType::Char_U:
1159 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001160 case BuiltinType::Char16:
1161 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001162 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001163 case BuiltinType::UInt:
1164 case BuiltinType::ULong:
1165 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001166 case BuiltinType::UInt128:
1167 case BuiltinType::Char_S:
1168 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001169 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001170 case BuiltinType::Short:
1171 case BuiltinType::Int:
1172 case BuiltinType::Long:
1173 case BuiltinType::LongLong:
1174 case BuiltinType::Int128:
1175 case BuiltinType::Float:
1176 case BuiltinType::Double:
1177 case BuiltinType::LongDouble:
1178 case BuiltinType::NullPtr:
1179 case BuiltinType::Overload:
1180 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001181 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001182
1183 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001184 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001185
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001186 case BuiltinType::ObjCId:
1187 VisitType = Context.getObjCIdType();
1188 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001189
1190 case BuiltinType::ObjCClass:
1191 VisitType = Context.getObjCClassType();
1192 break;
1193
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001194 case BuiltinType::ObjCSel:
1195 VisitType = Context.getObjCSelType();
1196 break;
1197 }
1198
1199 if (!VisitType.isNull()) {
1200 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001201 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001202 TU));
1203 }
1204
1205 return false;
1206}
1207
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001208bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1209 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1210}
1211
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001212bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1213 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1214}
1215
1216bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1217 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1218}
1219
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001220bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1221 // FIXME: We can't visit the template template parameter, but there's
1222 // no context information with which we can match up the depth/index in the
1223 // type to the appropriate
1224 return false;
1225}
1226
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001227bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1228 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1229 return true;
1230
John McCallc12c5bb2010-05-15 11:32:37 +00001231 return false;
1232}
1233
1234bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1235 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1236 return true;
1237
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001238 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1239 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1240 TU)))
1241 return true;
1242 }
1243
1244 return false;
1245}
1246
1247bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001248 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001249}
1250
1251bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1252 return Visit(TL.getPointeeLoc());
1253}
1254
1255bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1256 return Visit(TL.getPointeeLoc());
1257}
1258
1259bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1260 return Visit(TL.getPointeeLoc());
1261}
1262
1263bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001264 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001265}
1266
1267bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001268 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001269}
1270
Douglas Gregor01829d32010-08-31 14:41:23 +00001271bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1272 bool SkipResultType) {
1273 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001274 return true;
1275
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001276 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001277 if (Decl *D = TL.getArg(I))
1278 if (Visit(MakeCXCursor(D, TU)))
1279 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001280
1281 return false;
1282}
1283
1284bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1285 if (Visit(TL.getElementLoc()))
1286 return true;
1287
1288 if (Expr *Size = TL.getSizeExpr())
1289 return Visit(MakeCXCursor(Size, StmtParent, TU));
1290
1291 return false;
1292}
1293
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001294bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1295 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001296 // Visit the template name.
1297 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1298 TL.getTemplateNameLoc()))
1299 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001300
1301 // Visit the template arguments.
1302 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1303 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1304 return true;
1305
1306 return false;
1307}
1308
Douglas Gregor2332c112010-01-21 20:48:56 +00001309bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1310 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1311}
1312
1313bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1314 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1315 return Visit(TSInfo->getTypeLoc());
1316
1317 return false;
1318}
1319
Douglas Gregora59e3902010-01-21 23:27:09 +00001320bool CursorVisitor::VisitStmt(Stmt *S) {
1321 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1322 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001323 if (Stmt *C = *Child)
1324 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1325 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001326 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001327
Douglas Gregora59e3902010-01-21 23:27:09 +00001328 return false;
1329}
1330
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001331bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1332 // Specially handle CaseStmts because they can be nested, e.g.:
1333 //
1334 // case 1:
1335 // case 2:
1336 //
1337 // In this case the second CaseStmt is the child of the first. Walking
1338 // these recursively can blow out the stack.
1339 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1340 while (true) {
1341 // Set the Parent field to Cursor, then back to its old value once we're
1342 // done.
1343 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1344
1345 if (Stmt *LHS = S->getLHS())
1346 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1347 return true;
1348 if (Stmt *RHS = S->getRHS())
1349 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1350 return true;
1351 if (Stmt *SubStmt = S->getSubStmt()) {
1352 if (!isa<CaseStmt>(SubStmt))
1353 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1354
1355 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1356 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1357 Cursor = MakeCXCursor(CS, StmtParent, TU);
1358 if (RegionOfInterest.isValid()) {
1359 SourceRange Range = CS->getSourceRange();
1360 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1361 return false;
1362 }
1363
1364 switch (Visitor(Cursor, Parent, ClientData)) {
1365 case CXChildVisit_Break: return true;
1366 case CXChildVisit_Continue: return false;
1367 case CXChildVisit_Recurse:
1368 // Perform tail-recursion manually.
1369 S = CS;
1370 continue;
1371 }
1372 }
1373 return false;
1374 }
1375}
1376
Douglas Gregora59e3902010-01-21 23:27:09 +00001377bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1378 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1379 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001380 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001381 return true;
1382 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001383
Douglas Gregora59e3902010-01-21 23:27:09 +00001384 return false;
1385}
1386
Douglas Gregorf5bab412010-01-22 01:00:11 +00001387bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1388 if (VarDecl *Var = S->getConditionVariable()) {
1389 if (Visit(MakeCXCursor(Var, TU)))
1390 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001391 }
1392
Douglas Gregor263b47b2010-01-25 16:12:32 +00001393 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1394 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001395 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1396 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001397 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1398 return true;
1399
1400 return false;
1401}
1402
1403bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1404 if (VarDecl *Var = S->getConditionVariable()) {
1405 if (Visit(MakeCXCursor(Var, TU)))
1406 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001407 }
1408
Douglas Gregor263b47b2010-01-25 16:12:32 +00001409 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1410 return true;
1411 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1412 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001413
Douglas Gregor263b47b2010-01-25 16:12:32 +00001414 return false;
1415}
1416
1417bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1418 if (VarDecl *Var = S->getConditionVariable()) {
1419 if (Visit(MakeCXCursor(Var, TU)))
1420 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001421 }
1422
Douglas Gregor263b47b2010-01-25 16:12:32 +00001423 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1424 return true;
1425 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001426 return true;
1427
Douglas Gregor263b47b2010-01-25 16:12:32 +00001428 return false;
1429}
1430
1431bool CursorVisitor::VisitForStmt(ForStmt *S) {
1432 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1433 return true;
1434 if (VarDecl *Var = S->getConditionVariable()) {
1435 if (Visit(MakeCXCursor(Var, TU)))
1436 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001437 }
1438
Douglas Gregor263b47b2010-01-25 16:12:32 +00001439 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1440 return true;
1441 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1442 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001443 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1444 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001445
Douglas Gregorf5bab412010-01-22 01:00:11 +00001446 return false;
1447}
1448
Douglas Gregor8947a752010-09-02 20:35:02 +00001449bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1450 // Visit nested-name-specifier, if present.
1451 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1452 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1453 return true;
1454
1455 // Visit declaration name.
1456 if (VisitDeclarationNameInfo(E->getNameInfo()))
1457 return true;
1458
1459 // Visit explicitly-specified template arguments.
1460 if (E->hasExplicitTemplateArgs()) {
1461 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1462 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1463 *ArgEnd = Arg + Args.NumTemplateArgs;
1464 Arg != ArgEnd; ++Arg)
1465 if (VisitTemplateArgumentLoc(*Arg))
1466 return true;
1467 }
1468
1469 return false;
1470}
1471
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001472bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1473 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1474 return true;
1475
1476 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1477 return true;
1478
1479 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1480 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1481 return true;
1482
1483 return false;
1484}
1485
Ted Kremenek3064ef92010-08-27 21:34:58 +00001486bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1487 if (D->isDefinition()) {
1488 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1489 E = D->bases_end(); I != E; ++I) {
1490 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1491 return true;
1492 }
1493 }
1494
1495 return VisitTagDecl(D);
1496}
1497
1498
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001499bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1500 return Visit(B->getBlockDecl());
1501}
1502
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001503bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1504 // FIXME: Visit fields as well?
1505 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1506 return true;
1507
1508 return VisitExpr(E);
1509}
1510
Douglas Gregor336fd812010-01-23 00:40:08 +00001511bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1512 if (E->isArgumentType()) {
1513 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1514 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001515
Douglas Gregor336fd812010-01-23 00:40:08 +00001516 return false;
1517 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001518
Douglas Gregor336fd812010-01-23 00:40:08 +00001519 return VisitExpr(E);
1520}
1521
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001522bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1523 // Visit the base expression.
1524 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1525 return true;
1526
1527 // Visit the nested-name-specifier
1528 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1529 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1530 return true;
1531
1532 // Visit the declaration name.
1533 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1534 return true;
1535
1536 // Visit the explicitly-specified template arguments, if any.
1537 if (E->hasExplicitTemplateArgs()) {
1538 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1539 *ArgEnd = Arg + E->getNumTemplateArgs();
1540 Arg != ArgEnd;
1541 ++Arg) {
1542 if (VisitTemplateArgumentLoc(*Arg))
1543 return true;
1544 }
1545 }
1546
1547 return false;
1548}
1549
Douglas Gregor336fd812010-01-23 00:40:08 +00001550bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1551 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1552 if (Visit(TSInfo->getTypeLoc()))
1553 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001554
Douglas Gregor336fd812010-01-23 00:40:08 +00001555 return VisitCastExpr(E);
1556}
1557
1558bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1559 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1560 if (Visit(TSInfo->getTypeLoc()))
1561 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001562
Douglas Gregor336fd812010-01-23 00:40:08 +00001563 return VisitExpr(E);
1564}
1565
Douglas Gregor648220e2010-08-10 15:02:34 +00001566bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1567 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1568 Visit(E->getArgTInfo2()->getTypeLoc());
1569}
1570
1571bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1572 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1573 return true;
1574
1575 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1576}
1577
Douglas Gregor94802292010-09-02 21:20:16 +00001578bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1579 if (E->isTypeOperand()) {
1580 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1581 return Visit(TSInfo->getTypeLoc());
1582
1583 return false;
1584 }
1585
1586 return VisitExpr(E);
1587}
1588
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001589bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1590 // Visit base expression.
1591 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1592 return true;
1593
1594 // Visit the nested-name-specifier.
1595 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1596 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1597 return true;
1598
1599 // Visit the scope type that looks disturbingly like the nested-name-specifier
1600 // but isn't.
1601 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1602 if (Visit(TSInfo->getTypeLoc()))
1603 return true;
1604
1605 // Visit the name of the type being destroyed.
1606 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1607 if (Visit(TSInfo->getTypeLoc()))
1608 return true;
1609
1610 return false;
1611}
1612
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001613bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001614 // Visit the nested-name-specifier.
1615 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1616 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1617 return true;
1618
1619 // Visit the declaration name.
1620 if (VisitDeclarationNameInfo(E->getNameInfo()))
1621 return true;
1622
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001623 // Visit the explicitly-specified template arguments.
1624 if (const ExplicitTemplateArgumentList *ArgList
1625 = E->getOptionalExplicitTemplateArgs()) {
1626 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1627 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1628 Arg != ArgEnd; ++Arg) {
1629 if (VisitTemplateArgumentLoc(*Arg))
1630 return true;
1631 }
1632 }
1633
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001634 // FIXME: We don't have a way to visit all of the declarations referenced
1635 // here.
1636 return false;
1637}
1638
Douglas Gregorc2350e52010-03-08 16:40:19 +00001639bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001640 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1641 if (Visit(TSInfo->getTypeLoc()))
1642 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001643
1644 return VisitExpr(E);
1645}
1646
Douglas Gregor81d34662010-04-20 15:39:42 +00001647bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1648 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1649}
1650
1651
Ted Kremenek09dfa372010-02-18 05:46:33 +00001652bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001653 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1654 i != e; ++i)
1655 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001656 return true;
1657
1658 return false;
1659}
1660
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001661extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001662CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1663 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001664 // We use crash recovery to make some of our APIs more reliable, implicitly
1665 // enable it.
1666 llvm::CrashRecoveryContext::Enable();
1667
Douglas Gregora030b7c2010-01-22 20:35:53 +00001668 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001669 if (excludeDeclarationsFromPCH)
1670 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001671 if (displayDiagnostics)
1672 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001673 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001674}
1675
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001676void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001677 if (CIdx)
1678 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001679 if (getenv("LIBCLANG_TIMING"))
1680 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001681}
1682
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001683void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001684 if (CIdx) {
1685 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1686 CXXIdx->setUseExternalASTGeneration(value);
1687 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001688}
1689
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001690CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001691 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001692 if (!CIdx)
1693 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001694
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001695 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001696
Douglas Gregor28019772010-04-05 23:52:57 +00001697 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001698 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001699 CXXIdx->getOnlyLocalDecls(),
1700 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001701}
1702
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001703unsigned clang_defaultEditingTranslationUnitOptions() {
1704 return CXTranslationUnit_PrecompiledPreamble;
1705}
1706
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001707CXTranslationUnit
1708clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1709 const char *source_filename,
1710 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001711 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001712 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001713 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001714 return clang_parseTranslationUnit(CIdx, source_filename,
1715 command_line_args, num_command_line_args,
1716 unsaved_files, num_unsaved_files,
1717 CXTranslationUnit_DetailedPreprocessingRecord);
1718}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001719
1720struct ParseTranslationUnitInfo {
1721 CXIndex CIdx;
1722 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001723 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001724 int num_command_line_args;
1725 struct CXUnsavedFile *unsaved_files;
1726 unsigned num_unsaved_files;
1727 unsigned options;
1728 CXTranslationUnit result;
1729};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001730static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001731 ParseTranslationUnitInfo *PTUI =
1732 static_cast<ParseTranslationUnitInfo*>(UserData);
1733 CXIndex CIdx = PTUI->CIdx;
1734 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001735 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001736 int num_command_line_args = PTUI->num_command_line_args;
1737 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1738 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1739 unsigned options = PTUI->options;
1740 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001741
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001742 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001743 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001744
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001745 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1746
Douglas Gregor44c181a2010-07-23 00:33:23 +00001747 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001748 bool CompleteTranslationUnit
1749 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001750 bool CacheCodeCompetionResults
1751 = options & CXTranslationUnit_CacheCompletionResults;
1752
Douglas Gregor5352ac02010-01-28 00:27:43 +00001753 // Configure the diagnostics.
1754 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001755 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1756 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001757
Douglas Gregor4db64a42010-01-23 00:14:00 +00001758 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1759 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001760 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001761 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001762 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001763 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1764 Buffer));
1765 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001766
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001767 if (!CXXIdx->getUseExternalASTGeneration()) {
1768 llvm::SmallVector<const char *, 16> Args;
1769
1770 // The 'source_filename' argument is optional. If the caller does not
1771 // specify it then it is assumed that the source file is specified
1772 // in the actual argument list.
1773 if (source_filename)
1774 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001775
1776 // Since the Clang C library is primarily used by batch tools dealing with
1777 // (often very broken) source code, where spell-checking can have a
1778 // significant negative impact on performance (particularly when
1779 // precompiled headers are involved), we disable it by default.
1780 // Note that we place this argument early in the list, so that it can be
1781 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001782 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001783
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001784 Args.insert(Args.end(), command_line_args,
1785 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001786
Douglas Gregor44c181a2010-07-23 00:33:23 +00001787 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001788 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1789 Args.push_back("-Xclang");
1790 Args.push_back("-detailed-preprocessing-record");
1791 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001792
Douglas Gregor5352ac02010-01-28 00:27:43 +00001793 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001794
Ted Kremenek29b72842010-01-07 22:49:05 +00001795#ifdef USE_CRASHTRACER
1796 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001797#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001798
Daniel Dunbar94220972009-12-05 02:17:18 +00001799 llvm::OwningPtr<ASTUnit> Unit(
1800 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001801 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001802 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001803 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001804 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001805 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001806 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001807 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001808 CompleteTranslationUnit,
1809 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001810
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001811 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001812 // Make sure to check that 'Unit' is non-NULL.
1813 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001814 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1815 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001816 D != DEnd; ++D) {
1817 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001818 CXString Msg = clang_formatDiagnostic(&Diag,
1819 clang_defaultDiagnosticDisplayOptions());
1820 fprintf(stderr, "%s\n", clang_getCString(Msg));
1821 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001822 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001823#ifdef LLVM_ON_WIN32
1824 // On Windows, force a flush, since there may be multiple copies of
1825 // stderr and stdout in the file system, all with different buffers
1826 // but writing to the same device.
1827 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001828#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001829 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001830 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001831
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001832 PTUI->result = Unit.take();
1833 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001834 }
1835
Ted Kremenek139ba862009-10-22 00:03:57 +00001836 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001837 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001838
Ted Kremenek139ba862009-10-22 00:03:57 +00001839 // First add the complete path to the 'clang' executable.
1840 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001841 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001842
Ted Kremenek139ba862009-10-22 00:03:57 +00001843 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001844 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001845
Ted Kremenek139ba862009-10-22 00:03:57 +00001846 // The 'source_filename' argument is optional. If the caller does not
1847 // specify it then it is assumed that the source file is specified
1848 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001849 if (source_filename)
1850 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001851
Steve Naroff37b5ac22009-10-15 20:50:09 +00001852 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001853 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001854 char astTmpFile[L_tmpnam];
1855 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001856
1857 // Since the Clang C library is primarily used by batch tools dealing with
1858 // (often very broken) source code, where spell-checking can have a
1859 // significant negative impact on performance (particularly when
1860 // precompiled headers are involved), we disable it by default.
1861 // Note that we place this argument early in the list, so that it can be
1862 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001863 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001864
Douglas Gregor4db64a42010-01-23 00:14:00 +00001865 // Remap any unsaved files to temporary files.
1866 std::vector<llvm::sys::Path> TemporaryFiles;
1867 std::vector<std::string> RemapArgs;
1868 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001869 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001870
Douglas Gregor4db64a42010-01-23 00:14:00 +00001871 // The pointers into the elements of RemapArgs are stable because we
1872 // won't be adding anything to RemapArgs after this point.
1873 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1874 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001875
Ted Kremenek139ba862009-10-22 00:03:57 +00001876 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1877 for (int i = 0; i < num_command_line_args; ++i)
1878 if (const char *arg = command_line_args[i]) {
1879 if (strcmp(arg, "-o") == 0) {
1880 ++i; // Also skip the matching argument.
1881 continue;
1882 }
1883 if (strcmp(arg, "-emit-ast") == 0 ||
1884 strcmp(arg, "-c") == 0 ||
1885 strcmp(arg, "-fsyntax-only") == 0) {
1886 continue;
1887 }
1888
1889 // Keep the argument.
1890 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001891 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001892
Douglas Gregord93256e2010-01-28 06:00:51 +00001893 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001894 char tmpFileResults[L_tmpnam];
1895 char *tmpResultsFileName = tmpnam(tmpFileResults);
1896 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001897 TemporaryFiles.push_back(DiagnosticsFile);
1898 argv.push_back("-fdiagnostics-binary");
1899
Douglas Gregor44c181a2010-07-23 00:33:23 +00001900 // Do we need the detailed preprocessing record?
1901 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1902 argv.push_back("-Xclang");
1903 argv.push_back("-detailed-preprocessing-record");
1904 }
1905
Ted Kremenek139ba862009-10-22 00:03:57 +00001906 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001907 argv.push_back(NULL);
1908
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001909 // Invoke 'clang'.
1910 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1911 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001912 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001913 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1914 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001915 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001916 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001917 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001918
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001919 if (!ErrMsg.empty()) {
1920 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001921 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001922 I != E; ++I) {
1923 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001924 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001925 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001926 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001927
Daniel Dunbar32141c82010-02-23 20:23:45 +00001928 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001929 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001930
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001931 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001932 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001933 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001934 RemappedFiles.size(),
1935 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001936 if (ATU) {
1937 LoadSerializedDiagnostics(DiagnosticsFile,
1938 num_unsaved_files, unsaved_files,
1939 ATU->getFileManager(),
1940 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001941 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001942 } else if (CXXIdx->getDisplayDiagnostics()) {
1943 // We failed to load the ASTUnit, but we can still deserialize the
1944 // diagnostics and emit them.
1945 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001946 Diagnostic Diag;
1947 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001948 // FIXME: Faked LangOpts!
1949 LangOptions LangOpts;
1950 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1951 LoadSerializedDiagnostics(DiagnosticsFile,
1952 num_unsaved_files, unsaved_files,
1953 FileMgr, SourceMgr, Diags);
1954 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1955 DEnd = Diags.end();
1956 D != DEnd; ++D) {
1957 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001958 CXString Msg = clang_formatDiagnostic(&Diag,
1959 clang_defaultDiagnosticDisplayOptions());
1960 fprintf(stderr, "%s\n", clang_getCString(Msg));
1961 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001962 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001963
1964#ifdef LLVM_ON_WIN32
1965 // On Windows, force a flush, since there may be multiple copies of
1966 // stderr and stdout in the file system, all with different buffers
1967 // but writing to the same device.
1968 fflush(stderr);
1969#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001970 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001971
Douglas Gregor313e26c2010-02-18 23:35:40 +00001972 if (ATU) {
1973 // Make the translation unit responsible for destroying all temporary files.
1974 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1975 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001976 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001977 } else {
1978 // Destroy all of the temporary files now; they can't be referenced any
1979 // longer.
1980 llvm::sys::Path(astTmpFile).eraseFromDisk();
1981 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1982 TemporaryFiles[i].eraseFromDisk();
1983 }
1984
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001985 PTUI->result = ATU;
1986}
1987CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1988 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001989 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001990 int num_command_line_args,
1991 struct CXUnsavedFile *unsaved_files,
1992 unsigned num_unsaved_files,
1993 unsigned options) {
1994 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1995 num_command_line_args, unsaved_files, num_unsaved_files,
1996 options, 0 };
1997 llvm::CrashRecoveryContext CRC;
1998
1999 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002000 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2001 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2002 fprintf(stderr, " 'command_line_args' : [");
2003 for (int i = 0; i != num_command_line_args; ++i) {
2004 if (i)
2005 fprintf(stderr, ", ");
2006 fprintf(stderr, "'%s'", command_line_args[i]);
2007 }
2008 fprintf(stderr, "],\n");
2009 fprintf(stderr, " 'unsaved_files' : [");
2010 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2011 if (i)
2012 fprintf(stderr, ", ");
2013 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2014 unsaved_files[i].Length);
2015 }
2016 fprintf(stderr, "],\n");
2017 fprintf(stderr, " 'options' : %d,\n", options);
2018 fprintf(stderr, "}\n");
2019
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002020 return 0;
2021 }
2022
2023 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002024}
2025
Douglas Gregor19998442010-08-13 15:35:05 +00002026unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2027 return CXSaveTranslationUnit_None;
2028}
2029
2030int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2031 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002032 if (!TU)
2033 return 1;
2034
2035 return static_cast<ASTUnit *>(TU)->Save(FileName);
2036}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002037
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002038void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002039 if (CTUnit) {
2040 // If the translation unit has been marked as unsafe to free, just discard
2041 // it.
2042 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2043 return;
2044
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002045 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002046 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002047}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002048
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002049unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2050 return CXReparse_None;
2051}
2052
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002053struct ReparseTranslationUnitInfo {
2054 CXTranslationUnit TU;
2055 unsigned num_unsaved_files;
2056 struct CXUnsavedFile *unsaved_files;
2057 unsigned options;
2058 int result;
2059};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002060static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002061 ReparseTranslationUnitInfo *RTUI =
2062 static_cast<ReparseTranslationUnitInfo*>(UserData);
2063 CXTranslationUnit TU = RTUI->TU;
2064 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2065 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2066 unsigned options = RTUI->options;
2067 (void) options;
2068 RTUI->result = 1;
2069
Douglas Gregorabc563f2010-07-19 21:46:24 +00002070 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002071 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002072
2073 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2074 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2075 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2076 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002077 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002078 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2079 Buffer));
2080 }
2081
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002082 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
2083 RemappedFiles.size()))
2084 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002085}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002086int clang_reparseTranslationUnit(CXTranslationUnit TU,
2087 unsigned num_unsaved_files,
2088 struct CXUnsavedFile *unsaved_files,
2089 unsigned options) {
2090 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2091 options, 0 };
2092 llvm::CrashRecoveryContext CRC;
2093
2094 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002095 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002096 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2097 return 1;
2098 }
2099
2100 return RTUI.result;
2101}
2102
Douglas Gregordf95a132010-08-09 20:45:32 +00002103
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002104CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002105 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002106 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002107
Steve Naroff77accc12009-09-03 18:19:54 +00002108 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002109 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002110}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002111
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002112CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002113 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002114 return Result;
2115}
2116
Ted Kremenekfb480492010-01-13 21:46:36 +00002117} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002118
Ted Kremenekfb480492010-01-13 21:46:36 +00002119//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002120// CXSourceLocation and CXSourceRange Operations.
2121//===----------------------------------------------------------------------===//
2122
Douglas Gregorb9790342010-01-22 21:44:22 +00002123extern "C" {
2124CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002125 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002126 return Result;
2127}
2128
2129unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002130 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2131 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2132 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002133}
2134
2135CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2136 CXFile file,
2137 unsigned line,
2138 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002139 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002140 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002141
Douglas Gregorb9790342010-01-22 21:44:22 +00002142 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2143 SourceLocation SLoc
2144 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002145 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002146 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002147
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002148 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002149}
2150
Douglas Gregor5352ac02010-01-28 00:27:43 +00002151CXSourceRange clang_getNullRange() {
2152 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2153 return Result;
2154}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002155
Douglas Gregor5352ac02010-01-28 00:27:43 +00002156CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2157 if (begin.ptr_data[0] != end.ptr_data[0] ||
2158 begin.ptr_data[1] != end.ptr_data[1])
2159 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002160
2161 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002162 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002163 return Result;
2164}
2165
Douglas Gregor46766dc2010-01-26 19:19:08 +00002166void clang_getInstantiationLocation(CXSourceLocation location,
2167 CXFile *file,
2168 unsigned *line,
2169 unsigned *column,
2170 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002171 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2172
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002173 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002174 if (file)
2175 *file = 0;
2176 if (line)
2177 *line = 0;
2178 if (column)
2179 *column = 0;
2180 if (offset)
2181 *offset = 0;
2182 return;
2183 }
2184
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002185 const SourceManager &SM =
2186 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002187 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002188
2189 if (file)
2190 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2191 if (line)
2192 *line = SM.getInstantiationLineNumber(InstLoc);
2193 if (column)
2194 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002195 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002196 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002197}
2198
Douglas Gregor1db19de2010-01-19 21:36:55 +00002199CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002200 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002201 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002202 return Result;
2203}
2204
2205CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002206 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002207 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002208 return Result;
2209}
2210
Douglas Gregorb9790342010-01-22 21:44:22 +00002211} // end: extern "C"
2212
Douglas Gregor1db19de2010-01-19 21:36:55 +00002213//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002214// CXFile Operations.
2215//===----------------------------------------------------------------------===//
2216
2217extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002218CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002219 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002220 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002221
Steve Naroff88145032009-10-27 14:35:18 +00002222 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002223 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002224}
2225
2226time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002227 if (!SFile)
2228 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002229
Steve Naroff88145032009-10-27 14:35:18 +00002230 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2231 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002232}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002233
Douglas Gregorb9790342010-01-22 21:44:22 +00002234CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2235 if (!tu)
2236 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002237
Douglas Gregorb9790342010-01-22 21:44:22 +00002238 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002239
Douglas Gregorb9790342010-01-22 21:44:22 +00002240 FileManager &FMgr = CXXUnit->getFileManager();
2241 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2242 return const_cast<FileEntry *>(File);
2243}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002244
Ted Kremenekfb480492010-01-13 21:46:36 +00002245} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002246
Ted Kremenekfb480492010-01-13 21:46:36 +00002247//===----------------------------------------------------------------------===//
2248// CXCursor Operations.
2249//===----------------------------------------------------------------------===//
2250
Ted Kremenekfb480492010-01-13 21:46:36 +00002251static Decl *getDeclFromExpr(Stmt *E) {
2252 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2253 return RefExpr->getDecl();
2254 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2255 return ME->getMemberDecl();
2256 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2257 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002258
Ted Kremenekfb480492010-01-13 21:46:36 +00002259 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2260 return getDeclFromExpr(CE->getCallee());
2261 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2262 return getDeclFromExpr(CE->getSubExpr());
2263 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2264 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002265
Ted Kremenekfb480492010-01-13 21:46:36 +00002266 return 0;
2267}
2268
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002269static SourceLocation getLocationFromExpr(Expr *E) {
2270 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2271 return /*FIXME:*/Msg->getLeftLoc();
2272 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2273 return DRE->getLocation();
2274 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2275 return Member->getMemberLoc();
2276 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2277 return Ivar->getLocation();
2278 return E->getLocStart();
2279}
2280
Ted Kremenekfb480492010-01-13 21:46:36 +00002281extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002282
2283unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002284 CXCursorVisitor visitor,
2285 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002286 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002287
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002288 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2289 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002290 return CursorVis.VisitChildren(parent);
2291}
2292
Douglas Gregor78205d42010-01-20 21:45:58 +00002293static CXString getDeclSpelling(Decl *D) {
2294 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2295 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002296 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002297
Douglas Gregor78205d42010-01-20 21:45:58 +00002298 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002299 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002300
Douglas Gregor78205d42010-01-20 21:45:58 +00002301 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2302 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2303 // and returns different names. NamedDecl returns the class name and
2304 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002305 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002306
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002307 if (isa<UsingDirectiveDecl>(D))
2308 return createCXString("");
2309
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002310 llvm::SmallString<1024> S;
2311 llvm::raw_svector_ostream os(S);
2312 ND->printName(os);
2313
2314 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002315}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002316
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002317CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002318 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002319 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002320
Steve Narofff334b4e2009-09-02 18:26:48 +00002321 if (clang_isReference(C.kind)) {
2322 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002323 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002324 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002325 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002326 }
2327 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002328 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002329 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002330 }
2331 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002332 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002333 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002334 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002335 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002336 case CXCursor_CXXBaseSpecifier: {
2337 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2338 return createCXString(B->getType().getAsString());
2339 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002340 case CXCursor_TypeRef: {
2341 TypeDecl *Type = getCursorTypeRef(C).first;
2342 assert(Type && "Missing type decl");
2343
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002344 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2345 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002346 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002347 case CXCursor_TemplateRef: {
2348 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002349 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002350
2351 return createCXString(Template->getNameAsString());
2352 }
Douglas Gregor69319002010-08-31 23:48:11 +00002353
2354 case CXCursor_NamespaceRef: {
2355 NamedDecl *NS = getCursorNamespaceRef(C).first;
2356 assert(NS && "Missing namespace decl");
2357
2358 return createCXString(NS->getNameAsString());
2359 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002360
Daniel Dunbaracca7252009-11-30 20:42:49 +00002361 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002362 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002363 }
2364 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002365
2366 if (clang_isExpression(C.kind)) {
2367 Decl *D = getDeclFromExpr(getCursorExpr(C));
2368 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002369 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002370 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002371 }
2372
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002373 if (C.kind == CXCursor_MacroInstantiation)
2374 return createCXString(getCursorMacroInstantiation(C)->getName()
2375 ->getNameStart());
2376
Douglas Gregor572feb22010-03-18 18:04:21 +00002377 if (C.kind == CXCursor_MacroDefinition)
2378 return createCXString(getCursorMacroDefinition(C)->getName()
2379 ->getNameStart());
2380
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002381 if (clang_isDeclaration(C.kind))
2382 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002383
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002384 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002385}
2386
Ted Kremeneke68fff62010-02-17 00:41:32 +00002387CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002388 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002389 case CXCursor_FunctionDecl:
2390 return createCXString("FunctionDecl");
2391 case CXCursor_TypedefDecl:
2392 return createCXString("TypedefDecl");
2393 case CXCursor_EnumDecl:
2394 return createCXString("EnumDecl");
2395 case CXCursor_EnumConstantDecl:
2396 return createCXString("EnumConstantDecl");
2397 case CXCursor_StructDecl:
2398 return createCXString("StructDecl");
2399 case CXCursor_UnionDecl:
2400 return createCXString("UnionDecl");
2401 case CXCursor_ClassDecl:
2402 return createCXString("ClassDecl");
2403 case CXCursor_FieldDecl:
2404 return createCXString("FieldDecl");
2405 case CXCursor_VarDecl:
2406 return createCXString("VarDecl");
2407 case CXCursor_ParmDecl:
2408 return createCXString("ParmDecl");
2409 case CXCursor_ObjCInterfaceDecl:
2410 return createCXString("ObjCInterfaceDecl");
2411 case CXCursor_ObjCCategoryDecl:
2412 return createCXString("ObjCCategoryDecl");
2413 case CXCursor_ObjCProtocolDecl:
2414 return createCXString("ObjCProtocolDecl");
2415 case CXCursor_ObjCPropertyDecl:
2416 return createCXString("ObjCPropertyDecl");
2417 case CXCursor_ObjCIvarDecl:
2418 return createCXString("ObjCIvarDecl");
2419 case CXCursor_ObjCInstanceMethodDecl:
2420 return createCXString("ObjCInstanceMethodDecl");
2421 case CXCursor_ObjCClassMethodDecl:
2422 return createCXString("ObjCClassMethodDecl");
2423 case CXCursor_ObjCImplementationDecl:
2424 return createCXString("ObjCImplementationDecl");
2425 case CXCursor_ObjCCategoryImplDecl:
2426 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002427 case CXCursor_CXXMethod:
2428 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002429 case CXCursor_UnexposedDecl:
2430 return createCXString("UnexposedDecl");
2431 case CXCursor_ObjCSuperClassRef:
2432 return createCXString("ObjCSuperClassRef");
2433 case CXCursor_ObjCProtocolRef:
2434 return createCXString("ObjCProtocolRef");
2435 case CXCursor_ObjCClassRef:
2436 return createCXString("ObjCClassRef");
2437 case CXCursor_TypeRef:
2438 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002439 case CXCursor_TemplateRef:
2440 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002441 case CXCursor_NamespaceRef:
2442 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002443 case CXCursor_UnexposedExpr:
2444 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002445 case CXCursor_BlockExpr:
2446 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002447 case CXCursor_DeclRefExpr:
2448 return createCXString("DeclRefExpr");
2449 case CXCursor_MemberRefExpr:
2450 return createCXString("MemberRefExpr");
2451 case CXCursor_CallExpr:
2452 return createCXString("CallExpr");
2453 case CXCursor_ObjCMessageExpr:
2454 return createCXString("ObjCMessageExpr");
2455 case CXCursor_UnexposedStmt:
2456 return createCXString("UnexposedStmt");
2457 case CXCursor_InvalidFile:
2458 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002459 case CXCursor_InvalidCode:
2460 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002461 case CXCursor_NoDeclFound:
2462 return createCXString("NoDeclFound");
2463 case CXCursor_NotImplemented:
2464 return createCXString("NotImplemented");
2465 case CXCursor_TranslationUnit:
2466 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002467 case CXCursor_UnexposedAttr:
2468 return createCXString("UnexposedAttr");
2469 case CXCursor_IBActionAttr:
2470 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002471 case CXCursor_IBOutletAttr:
2472 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002473 case CXCursor_IBOutletCollectionAttr:
2474 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002475 case CXCursor_PreprocessingDirective:
2476 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002477 case CXCursor_MacroDefinition:
2478 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002479 case CXCursor_MacroInstantiation:
2480 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002481 case CXCursor_Namespace:
2482 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002483 case CXCursor_LinkageSpec:
2484 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002485 case CXCursor_CXXBaseSpecifier:
2486 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002487 case CXCursor_Constructor:
2488 return createCXString("CXXConstructor");
2489 case CXCursor_Destructor:
2490 return createCXString("CXXDestructor");
2491 case CXCursor_ConversionFunction:
2492 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002493 case CXCursor_TemplateTypeParameter:
2494 return createCXString("TemplateTypeParameter");
2495 case CXCursor_NonTypeTemplateParameter:
2496 return createCXString("NonTypeTemplateParameter");
2497 case CXCursor_TemplateTemplateParameter:
2498 return createCXString("TemplateTemplateParameter");
2499 case CXCursor_FunctionTemplate:
2500 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002501 case CXCursor_ClassTemplate:
2502 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002503 case CXCursor_ClassTemplatePartialSpecialization:
2504 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002505 case CXCursor_NamespaceAlias:
2506 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002507 case CXCursor_UsingDirective:
2508 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002509 case CXCursor_UsingDeclaration:
2510 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002511 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002512
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002513 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002514 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002515}
Steve Naroff89922f82009-08-31 00:59:03 +00002516
Ted Kremeneke68fff62010-02-17 00:41:32 +00002517enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2518 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002519 CXClientData client_data) {
2520 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2521 *BestCursor = cursor;
2522 return CXChildVisit_Recurse;
2523}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002524
Douglas Gregorb9790342010-01-22 21:44:22 +00002525CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2526 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002527 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002528
Douglas Gregorb9790342010-01-22 21:44:22 +00002529 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002530 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2531
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002532 // Translate the given source location to make it point at the beginning of
2533 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002534 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002535
2536 // Guard against an invalid SourceLocation, or we may assert in one
2537 // of the following calls.
2538 if (SLoc.isInvalid())
2539 return clang_getNullCursor();
2540
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002541 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2542 CXXUnit->getASTContext().getLangOptions());
2543
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002544 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2545 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002546 // FIXME: Would be great to have a "hint" cursor, then walk from that
2547 // hint cursor upward until we find a cursor whose source range encloses
2548 // the region of interest, rather than starting from the translation unit.
2549 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002550 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002551 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002552 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002553 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002554 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002555}
2556
Ted Kremenek73885552009-11-17 19:28:59 +00002557CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002558 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002559}
2560
2561unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002562 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002563}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002564
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002565unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002566 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2567}
2568
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002569unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002570 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2571}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002572
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002573unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002574 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2575}
2576
Douglas Gregor97b98722010-01-19 23:20:36 +00002577unsigned clang_isExpression(enum CXCursorKind K) {
2578 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2579}
2580
2581unsigned clang_isStatement(enum CXCursorKind K) {
2582 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2583}
2584
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002585unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2586 return K == CXCursor_TranslationUnit;
2587}
2588
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002589unsigned clang_isPreprocessing(enum CXCursorKind K) {
2590 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2591}
2592
Ted Kremenekad6eff62010-03-08 21:17:29 +00002593unsigned clang_isUnexposed(enum CXCursorKind K) {
2594 switch (K) {
2595 case CXCursor_UnexposedDecl:
2596 case CXCursor_UnexposedExpr:
2597 case CXCursor_UnexposedStmt:
2598 case CXCursor_UnexposedAttr:
2599 return true;
2600 default:
2601 return false;
2602 }
2603}
2604
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002605CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002606 return C.kind;
2607}
2608
Douglas Gregor98258af2010-01-18 22:46:11 +00002609CXSourceLocation clang_getCursorLocation(CXCursor C) {
2610 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002611 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002612 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002613 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2614 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002615 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002616 }
2617
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002618 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002619 std::pair<ObjCProtocolDecl *, SourceLocation> P
2620 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002621 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002622 }
2623
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002624 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002625 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2626 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002627 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002628 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002629
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002630 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002631 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002632 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002633 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002634
2635 case CXCursor_TemplateRef: {
2636 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2637 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2638 }
2639
Douglas Gregor69319002010-08-31 23:48:11 +00002640 case CXCursor_NamespaceRef: {
2641 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2642 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2643 }
2644
Ted Kremenek3064ef92010-08-27 21:34:58 +00002645 case CXCursor_CXXBaseSpecifier: {
2646 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2647 return clang_getNullLocation();
2648 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002649
Douglas Gregorf46034a2010-01-18 23:41:10 +00002650 default:
2651 // FIXME: Need a way to enumerate all non-reference cases.
2652 llvm_unreachable("Missed a reference kind");
2653 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002654 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002655
2656 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002657 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002658 getLocationFromExpr(getCursorExpr(C)));
2659
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002660 if (C.kind == CXCursor_PreprocessingDirective) {
2661 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2662 return cxloc::translateSourceLocation(getCursorContext(C), L);
2663 }
Douglas Gregor48072312010-03-18 15:23:44 +00002664
2665 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002666 SourceLocation L
2667 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002668 return cxloc::translateSourceLocation(getCursorContext(C), L);
2669 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002670
2671 if (C.kind == CXCursor_MacroDefinition) {
2672 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2673 return cxloc::translateSourceLocation(getCursorContext(C), L);
2674 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002675
Ted Kremenek9a700d22010-05-12 06:16:13 +00002676 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002677 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002678
Douglas Gregorf46034a2010-01-18 23:41:10 +00002679 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002680 SourceLocation Loc = D->getLocation();
2681 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2682 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002683 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002684}
Douglas Gregora7bde202010-01-19 00:34:46 +00002685
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002686} // end extern "C"
2687
2688static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002689 if (clang_isReference(C.kind)) {
2690 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002691 case CXCursor_ObjCSuperClassRef:
2692 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002693
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002694 case CXCursor_ObjCProtocolRef:
2695 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002696
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002697 case CXCursor_ObjCClassRef:
2698 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002699
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002700 case CXCursor_TypeRef:
2701 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002702
2703 case CXCursor_TemplateRef:
2704 return getCursorTemplateRef(C).second;
2705
Douglas Gregor69319002010-08-31 23:48:11 +00002706 case CXCursor_NamespaceRef:
2707 return getCursorNamespaceRef(C).second;
2708
Ted Kremenek3064ef92010-08-27 21:34:58 +00002709 case CXCursor_CXXBaseSpecifier:
2710 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2711 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002712
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002713 default:
2714 // FIXME: Need a way to enumerate all non-reference cases.
2715 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002716 }
2717 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002718
2719 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002720 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002721
2722 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002723 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002724
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002725 if (C.kind == CXCursor_PreprocessingDirective)
2726 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002727
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002728 if (C.kind == CXCursor_MacroInstantiation)
2729 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002730
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002731 if (C.kind == CXCursor_MacroDefinition)
2732 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002733
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002734 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2735 return getCursorDecl(C)->getSourceRange();
2736
2737 return SourceRange();
2738}
2739
2740extern "C" {
2741
2742CXSourceRange clang_getCursorExtent(CXCursor C) {
2743 SourceRange R = getRawCursorExtent(C);
2744 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002745 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002746
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002747 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002748}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002749
2750CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002751 if (clang_isInvalid(C.kind))
2752 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002753
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002754 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002755 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002756 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002757
Douglas Gregor97b98722010-01-19 23:20:36 +00002758 if (clang_isExpression(C.kind)) {
2759 Decl *D = getDeclFromExpr(getCursorExpr(C));
2760 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002761 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002762 return clang_getNullCursor();
2763 }
2764
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002765 if (C.kind == CXCursor_MacroInstantiation) {
2766 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2767 return MakeMacroDefinitionCursor(Def, CXXUnit);
2768 }
2769
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002770 if (!clang_isReference(C.kind))
2771 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002772
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002773 switch (C.kind) {
2774 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002775 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002776
2777 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002778 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002779
2780 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002781 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002782
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002783 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002784 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002785
2786 case CXCursor_TemplateRef:
2787 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2788
Douglas Gregor69319002010-08-31 23:48:11 +00002789 case CXCursor_NamespaceRef:
2790 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2791
Ted Kremenek3064ef92010-08-27 21:34:58 +00002792 case CXCursor_CXXBaseSpecifier: {
2793 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2794 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2795 CXXUnit));
2796 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002797
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002798 default:
2799 // We would prefer to enumerate all non-reference cursor kinds here.
2800 llvm_unreachable("Unhandled reference cursor kind");
2801 break;
2802 }
2803 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002804
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002805 return clang_getNullCursor();
2806}
2807
Douglas Gregorb6998662010-01-19 19:34:47 +00002808CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002809 if (clang_isInvalid(C.kind))
2810 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002811
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002812 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002813
Douglas Gregorb6998662010-01-19 19:34:47 +00002814 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002815 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002816 C = clang_getCursorReferenced(C);
2817 WasReference = true;
2818 }
2819
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002820 if (C.kind == CXCursor_MacroInstantiation)
2821 return clang_getCursorReferenced(C);
2822
Douglas Gregorb6998662010-01-19 19:34:47 +00002823 if (!clang_isDeclaration(C.kind))
2824 return clang_getNullCursor();
2825
2826 Decl *D = getCursorDecl(C);
2827 if (!D)
2828 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002829
Douglas Gregorb6998662010-01-19 19:34:47 +00002830 switch (D->getKind()) {
2831 // Declaration kinds that don't really separate the notions of
2832 // declaration and definition.
2833 case Decl::Namespace:
2834 case Decl::Typedef:
2835 case Decl::TemplateTypeParm:
2836 case Decl::EnumConstant:
2837 case Decl::Field:
2838 case Decl::ObjCIvar:
2839 case Decl::ObjCAtDefsField:
2840 case Decl::ImplicitParam:
2841 case Decl::ParmVar:
2842 case Decl::NonTypeTemplateParm:
2843 case Decl::TemplateTemplateParm:
2844 case Decl::ObjCCategoryImpl:
2845 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002846 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002847 case Decl::LinkageSpec:
2848 case Decl::ObjCPropertyImpl:
2849 case Decl::FileScopeAsm:
2850 case Decl::StaticAssert:
2851 case Decl::Block:
2852 return C;
2853
2854 // Declaration kinds that don't make any sense here, but are
2855 // nonetheless harmless.
2856 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002857 break;
2858
2859 // Declaration kinds for which the definition is not resolvable.
2860 case Decl::UnresolvedUsingTypename:
2861 case Decl::UnresolvedUsingValue:
2862 break;
2863
2864 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002865 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2866 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002867
2868 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002869 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002870
2871 case Decl::Enum:
2872 case Decl::Record:
2873 case Decl::CXXRecord:
2874 case Decl::ClassTemplateSpecialization:
2875 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002876 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002877 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002878 return clang_getNullCursor();
2879
2880 case Decl::Function:
2881 case Decl::CXXMethod:
2882 case Decl::CXXConstructor:
2883 case Decl::CXXDestructor:
2884 case Decl::CXXConversion: {
2885 const FunctionDecl *Def = 0;
2886 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002887 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002888 return clang_getNullCursor();
2889 }
2890
2891 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002892 // Ask the variable if it has a definition.
2893 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2894 return MakeCXCursor(Def, CXXUnit);
2895 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002896 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002897
Douglas Gregorb6998662010-01-19 19:34:47 +00002898 case Decl::FunctionTemplate: {
2899 const FunctionDecl *Def = 0;
2900 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002901 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002902 return clang_getNullCursor();
2903 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002904
Douglas Gregorb6998662010-01-19 19:34:47 +00002905 case Decl::ClassTemplate: {
2906 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002907 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002908 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002909 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002910 return clang_getNullCursor();
2911 }
2912
2913 case Decl::Using: {
2914 UsingDecl *Using = cast<UsingDecl>(D);
2915 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002916 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2917 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002918 S != SEnd; ++S) {
2919 if (Def != clang_getNullCursor()) {
2920 // FIXME: We have no way to return multiple results.
2921 return clang_getNullCursor();
2922 }
2923
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002924 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002925 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002926 }
2927
2928 return Def;
2929 }
2930
2931 case Decl::UsingShadow:
2932 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002933 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002934 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002935
2936 case Decl::ObjCMethod: {
2937 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2938 if (Method->isThisDeclarationADefinition())
2939 return C;
2940
2941 // Dig out the method definition in the associated
2942 // @implementation, if we have it.
2943 // FIXME: The ASTs should make finding the definition easier.
2944 if (ObjCInterfaceDecl *Class
2945 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2946 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2947 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2948 Method->isInstanceMethod()))
2949 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002950 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002951
2952 return clang_getNullCursor();
2953 }
2954
2955 case Decl::ObjCCategory:
2956 if (ObjCCategoryImplDecl *Impl
2957 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002958 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002959 return clang_getNullCursor();
2960
2961 case Decl::ObjCProtocol:
2962 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2963 return C;
2964 return clang_getNullCursor();
2965
2966 case Decl::ObjCInterface:
2967 // There are two notions of a "definition" for an Objective-C
2968 // class: the interface and its implementation. When we resolved a
2969 // reference to an Objective-C class, produce the @interface as
2970 // the definition; when we were provided with the interface,
2971 // produce the @implementation as the definition.
2972 if (WasReference) {
2973 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2974 return C;
2975 } else if (ObjCImplementationDecl *Impl
2976 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002977 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002978 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002979
Douglas Gregorb6998662010-01-19 19:34:47 +00002980 case Decl::ObjCProperty:
2981 // FIXME: We don't really know where to find the
2982 // ObjCPropertyImplDecls that implement this property.
2983 return clang_getNullCursor();
2984
2985 case Decl::ObjCCompatibleAlias:
2986 if (ObjCInterfaceDecl *Class
2987 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2988 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002989 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002990
Douglas Gregorb6998662010-01-19 19:34:47 +00002991 return clang_getNullCursor();
2992
2993 case Decl::ObjCForwardProtocol: {
2994 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2995 if (Forward->protocol_size() == 1)
2996 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002997 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002998 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002999
3000 // FIXME: Cannot return multiple definitions.
3001 return clang_getNullCursor();
3002 }
3003
3004 case Decl::ObjCClass: {
3005 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
3006 if (Class->size() == 1) {
3007 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
3008 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003009 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003010 return clang_getNullCursor();
3011 }
3012
3013 // FIXME: Cannot return multiple definitions.
3014 return clang_getNullCursor();
3015 }
3016
3017 case Decl::Friend:
3018 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003019 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003020 return clang_getNullCursor();
3021
3022 case Decl::FriendTemplate:
3023 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003024 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003025 return clang_getNullCursor();
3026 }
3027
3028 return clang_getNullCursor();
3029}
3030
3031unsigned clang_isCursorDefinition(CXCursor C) {
3032 if (!clang_isDeclaration(C.kind))
3033 return 0;
3034
3035 return clang_getCursorDefinition(C) == C;
3036}
3037
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003038void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003039 const char **startBuf,
3040 const char **endBuf,
3041 unsigned *startLine,
3042 unsigned *startColumn,
3043 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003044 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003045 assert(getCursorDecl(C) && "CXCursor has null decl");
3046 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003047 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3048 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003049
Steve Naroff4ade6d62009-09-23 17:52:52 +00003050 SourceManager &SM = FD->getASTContext().getSourceManager();
3051 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3052 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3053 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3054 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3055 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3056 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3057}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003058
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003059void clang_enableStackTraces(void) {
3060 llvm::sys::PrintStackTraceOnErrorSignal();
3061}
3062
Ted Kremenekfb480492010-01-13 21:46:36 +00003063} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003064
Ted Kremenekfb480492010-01-13 21:46:36 +00003065//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003066// Token-based Operations.
3067//===----------------------------------------------------------------------===//
3068
3069/* CXToken layout:
3070 * int_data[0]: a CXTokenKind
3071 * int_data[1]: starting token location
3072 * int_data[2]: token length
3073 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003074 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003075 * otherwise unused.
3076 */
3077extern "C" {
3078
3079CXTokenKind clang_getTokenKind(CXToken CXTok) {
3080 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3081}
3082
3083CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3084 switch (clang_getTokenKind(CXTok)) {
3085 case CXToken_Identifier:
3086 case CXToken_Keyword:
3087 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003088 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3089 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003090
3091 case CXToken_Literal: {
3092 // We have stashed the starting pointer in the ptr_data field. Use it.
3093 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003094 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003095 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003096
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003097 case CXToken_Punctuation:
3098 case CXToken_Comment:
3099 break;
3100 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003101
3102 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003103 // deconstructing the source location.
3104 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3105 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003106 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003107
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003108 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3109 std::pair<FileID, unsigned> LocInfo
3110 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003111 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003112 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003113 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3114 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003115 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003116
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003117 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003118}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003119
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003120CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3121 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3122 if (!CXXUnit)
3123 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003124
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003125 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3126 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3127}
3128
3129CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3130 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003131 if (!CXXUnit)
3132 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003133
3134 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003135 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3136}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003137
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003138void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3139 CXToken **Tokens, unsigned *NumTokens) {
3140 if (Tokens)
3141 *Tokens = 0;
3142 if (NumTokens)
3143 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003144
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003145 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3146 if (!CXXUnit || !Tokens || !NumTokens)
3147 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003148
Douglas Gregorbdf60622010-03-05 21:16:25 +00003149 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3150
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003151 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003152 if (R.isInvalid())
3153 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003154
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003155 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3156 std::pair<FileID, unsigned> BeginLocInfo
3157 = SourceMgr.getDecomposedLoc(R.getBegin());
3158 std::pair<FileID, unsigned> EndLocInfo
3159 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003160
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003161 // Cannot tokenize across files.
3162 if (BeginLocInfo.first != EndLocInfo.first)
3163 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003164
3165 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003166 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003167 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003168 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003169 if (Invalid)
3170 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003171
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003172 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3173 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003174 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003175 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003176
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003177 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003178 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003179 llvm::SmallVector<CXToken, 32> CXTokens;
3180 Token Tok;
3181 do {
3182 // Lex the next token
3183 Lex.LexFromRawLexer(Tok);
3184 if (Tok.is(tok::eof))
3185 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003186
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003187 // Initialize the CXToken.
3188 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003189
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003190 // - Common fields
3191 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3192 CXTok.int_data[2] = Tok.getLength();
3193 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003194
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003195 // - Kind-specific fields
3196 if (Tok.isLiteral()) {
3197 CXTok.int_data[0] = CXToken_Literal;
3198 CXTok.ptr_data = (void *)Tok.getLiteralData();
3199 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003200 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003201 std::pair<FileID, unsigned> LocInfo
3202 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003203 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003204 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003205 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3206 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003207 return;
3208
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003209 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003210 IdentifierInfo *II
3211 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003212
3213 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3214 CXTok.int_data[0] = CXToken_Keyword;
3215 }
3216 else {
3217 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3218 CXToken_Identifier
3219 : CXToken_Keyword;
3220 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003221 CXTok.ptr_data = II;
3222 } else if (Tok.is(tok::comment)) {
3223 CXTok.int_data[0] = CXToken_Comment;
3224 CXTok.ptr_data = 0;
3225 } else {
3226 CXTok.int_data[0] = CXToken_Punctuation;
3227 CXTok.ptr_data = 0;
3228 }
3229 CXTokens.push_back(CXTok);
3230 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003231
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003232 if (CXTokens.empty())
3233 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003234
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003235 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3236 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3237 *NumTokens = CXTokens.size();
3238}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003239
Ted Kremenek6db61092010-05-05 00:55:15 +00003240void clang_disposeTokens(CXTranslationUnit TU,
3241 CXToken *Tokens, unsigned NumTokens) {
3242 free(Tokens);
3243}
3244
3245} // end: extern "C"
3246
3247//===----------------------------------------------------------------------===//
3248// Token annotation APIs.
3249//===----------------------------------------------------------------------===//
3250
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003251typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003252static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3253 CXCursor parent,
3254 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003255namespace {
3256class AnnotateTokensWorker {
3257 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003258 CXToken *Tokens;
3259 CXCursor *Cursors;
3260 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003261 unsigned TokIdx;
3262 CursorVisitor AnnotateVis;
3263 SourceManager &SrcMgr;
3264
3265 bool MoreTokens() const { return TokIdx < NumTokens; }
3266 unsigned NextToken() const { return TokIdx; }
3267 void AdvanceToken() { ++TokIdx; }
3268 SourceLocation GetTokenLoc(unsigned tokI) {
3269 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3270 }
3271
Ted Kremenek6db61092010-05-05 00:55:15 +00003272public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003273 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003274 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3275 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003276 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003277 NumTokens(numTokens), TokIdx(0),
3278 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3279 Decl::MaxPCHLevel, RegionOfInterest),
3280 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003281
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003282 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003283 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003284 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003285};
3286}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003287
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003288void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3289 // Walk the AST within the region of interest, annotating tokens
3290 // along the way.
3291 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003292
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003293 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3294 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3295 if (Pos != Annotated.end())
3296 Cursors[I] = Pos->second;
3297 }
3298
3299 // Finish up annotating any tokens left.
3300 if (!MoreTokens())
3301 return;
3302
3303 const CXCursor &C = clang_getNullCursor();
3304 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3305 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3306 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003307 }
3308}
3309
Ted Kremenek6db61092010-05-05 00:55:15 +00003310enum CXChildVisitResult
3311AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003312 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3313 // We can always annotate a preprocessing directive/macro instantiation.
3314 if (clang_isPreprocessing(cursor.kind)) {
3315 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003316 return CXChildVisit_Recurse;
3317 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003318
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003319 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003320
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003321 if (cursorRange.isInvalid())
3322 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003323
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003324 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3325
Ted Kremeneka333c662010-05-12 05:29:33 +00003326 // Adjust the annotated range based specific declarations.
3327 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3328 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003329 Decl *D = cxcursor::getCursorDecl(cursor);
3330 // Don't visit synthesized ObjC methods, since they have no syntatic
3331 // representation in the source.
3332 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3333 if (MD->isSynthesized())
3334 return CXChildVisit_Continue;
3335 }
3336 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003337 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3338 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003339 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003340 if (TLoc.isValid() &&
3341 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003342 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003343 }
3344 }
3345 }
3346
Ted Kremenek3f404602010-08-14 01:14:06 +00003347 // If the location of the cursor occurs within a macro instantiation, record
3348 // the spelling location of the cursor in our annotation map. We can then
3349 // paper over the token labelings during a post-processing step to try and
3350 // get cursor mappings for tokens that are the *arguments* of a macro
3351 // instantiation.
3352 if (L.isMacroID()) {
3353 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3354 // Only invalidate the old annotation if it isn't part of a preprocessing
3355 // directive. Here we assume that the default construction of CXCursor
3356 // results in CXCursor.kind being an initialized value (i.e., 0). If
3357 // this isn't the case, we can fix by doing lookup + insertion.
3358
3359 CXCursor &oldC = Annotated[rawEncoding];
3360 if (!clang_isPreprocessing(oldC.kind))
3361 oldC = cursor;
3362 }
3363
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003364 const enum CXCursorKind K = clang_getCursorKind(parent);
3365 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003366 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3367 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003368
3369 while (MoreTokens()) {
3370 const unsigned I = NextToken();
3371 SourceLocation TokLoc = GetTokenLoc(I);
3372 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3373 case RangeBefore:
3374 Cursors[I] = updateC;
3375 AdvanceToken();
3376 continue;
3377 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003378 case RangeOverlap:
3379 break;
3380 }
3381 break;
3382 }
3383
3384 // Visit children to get their cursor information.
3385 const unsigned BeforeChildren = NextToken();
3386 VisitChildren(cursor);
3387 const unsigned AfterChildren = NextToken();
3388
3389 // Adjust 'Last' to the last token within the extent of the cursor.
3390 while (MoreTokens()) {
3391 const unsigned I = NextToken();
3392 SourceLocation TokLoc = GetTokenLoc(I);
3393 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3394 case RangeBefore:
3395 assert(0 && "Infeasible");
3396 case RangeAfter:
3397 break;
3398 case RangeOverlap:
3399 Cursors[I] = updateC;
3400 AdvanceToken();
3401 continue;
3402 }
3403 break;
3404 }
3405 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003406
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003407 // Scan the tokens that are at the beginning of the cursor, but are not
3408 // capture by the child cursors.
3409
3410 // For AST elements within macros, rely on a post-annotate pass to
3411 // to correctly annotate the tokens with cursors. Otherwise we can
3412 // get confusing results of having tokens that map to cursors that really
3413 // are expanded by an instantiation.
3414 if (L.isMacroID())
3415 cursor = clang_getNullCursor();
3416
3417 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3418 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3419 break;
3420 Cursors[I] = cursor;
3421 }
3422 // Scan the tokens that are at the end of the cursor, but are not captured
3423 // but the child cursors.
3424 for (unsigned I = AfterChildren; I != Last; ++I)
3425 Cursors[I] = cursor;
3426
3427 TokIdx = Last;
3428 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003429}
3430
Ted Kremenek6db61092010-05-05 00:55:15 +00003431static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3432 CXCursor parent,
3433 CXClientData client_data) {
3434 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3435}
3436
3437extern "C" {
3438
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003439void clang_annotateTokens(CXTranslationUnit TU,
3440 CXToken *Tokens, unsigned NumTokens,
3441 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003442
3443 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003444 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003445
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003446 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003447 if (!CXXUnit) {
3448 // Any token we don't specifically annotate will have a NULL cursor.
3449 const CXCursor &C = clang_getNullCursor();
3450 for (unsigned I = 0; I != NumTokens; ++I)
3451 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003452 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003453 }
3454
Douglas Gregorbdf60622010-03-05 21:16:25 +00003455 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003456
Douglas Gregor0396f462010-03-19 05:22:59 +00003457 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003458 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003459 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3460 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003461 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3462 clang_getTokenLocation(TU,
3463 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003464
Douglas Gregor0396f462010-03-19 05:22:59 +00003465 // A mapping from the source locations found when re-lexing or traversing the
3466 // region of interest to the corresponding cursors.
3467 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003468
3469 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003470 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003471 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3472 std::pair<FileID, unsigned> BeginLocInfo
3473 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3474 std::pair<FileID, unsigned> EndLocInfo
3475 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003476
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003477 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003478 bool Invalid = false;
3479 if (BeginLocInfo.first == EndLocInfo.first &&
3480 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3481 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003482 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3483 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003484 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003485 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003486 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003487
3488 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003489 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003490 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003491 Token Tok;
3492 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003493
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003494 reprocess:
3495 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3496 // We have found a preprocessing directive. Gobble it up so that we
3497 // don't see it while preprocessing these tokens later, but keep track of
3498 // all of the token locations inside this preprocessing directive so that
3499 // we can annotate them appropriately.
3500 //
3501 // FIXME: Some simple tests here could identify macro definitions and
3502 // #undefs, to provide specific cursor kinds for those.
3503 std::vector<SourceLocation> Locations;
3504 do {
3505 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003506 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003507 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003508
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003509 using namespace cxcursor;
3510 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003511 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3512 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003513 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003514 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3515 Annotated[Locations[I].getRawEncoding()] = Cursor;
3516 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003517
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003518 if (Tok.isAtStartOfLine())
3519 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003520
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003521 continue;
3522 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003523
Douglas Gregor48072312010-03-18 15:23:44 +00003524 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003525 break;
3526 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003527 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003528
Douglas Gregor0396f462010-03-19 05:22:59 +00003529 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003530 // a specific cursor.
3531 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3532 CXXUnit, RegionOfInterest);
3533 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003534}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003535} // end: extern "C"
3536
3537//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003538// Operations for querying linkage of a cursor.
3539//===----------------------------------------------------------------------===//
3540
3541extern "C" {
3542CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003543 if (!clang_isDeclaration(cursor.kind))
3544 return CXLinkage_Invalid;
3545
Ted Kremenek16b42592010-03-03 06:36:57 +00003546 Decl *D = cxcursor::getCursorDecl(cursor);
3547 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3548 switch (ND->getLinkage()) {
3549 case NoLinkage: return CXLinkage_NoLinkage;
3550 case InternalLinkage: return CXLinkage_Internal;
3551 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3552 case ExternalLinkage: return CXLinkage_External;
3553 };
3554
3555 return CXLinkage_Invalid;
3556}
3557} // end: extern "C"
3558
3559//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003560// Operations for querying language of a cursor.
3561//===----------------------------------------------------------------------===//
3562
3563static CXLanguageKind getDeclLanguage(const Decl *D) {
3564 switch (D->getKind()) {
3565 default:
3566 break;
3567 case Decl::ImplicitParam:
3568 case Decl::ObjCAtDefsField:
3569 case Decl::ObjCCategory:
3570 case Decl::ObjCCategoryImpl:
3571 case Decl::ObjCClass:
3572 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003573 case Decl::ObjCForwardProtocol:
3574 case Decl::ObjCImplementation:
3575 case Decl::ObjCInterface:
3576 case Decl::ObjCIvar:
3577 case Decl::ObjCMethod:
3578 case Decl::ObjCProperty:
3579 case Decl::ObjCPropertyImpl:
3580 case Decl::ObjCProtocol:
3581 return CXLanguage_ObjC;
3582 case Decl::CXXConstructor:
3583 case Decl::CXXConversion:
3584 case Decl::CXXDestructor:
3585 case Decl::CXXMethod:
3586 case Decl::CXXRecord:
3587 case Decl::ClassTemplate:
3588 case Decl::ClassTemplatePartialSpecialization:
3589 case Decl::ClassTemplateSpecialization:
3590 case Decl::Friend:
3591 case Decl::FriendTemplate:
3592 case Decl::FunctionTemplate:
3593 case Decl::LinkageSpec:
3594 case Decl::Namespace:
3595 case Decl::NamespaceAlias:
3596 case Decl::NonTypeTemplateParm:
3597 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003598 case Decl::TemplateTemplateParm:
3599 case Decl::TemplateTypeParm:
3600 case Decl::UnresolvedUsingTypename:
3601 case Decl::UnresolvedUsingValue:
3602 case Decl::Using:
3603 case Decl::UsingDirective:
3604 case Decl::UsingShadow:
3605 return CXLanguage_CPlusPlus;
3606 }
3607
3608 return CXLanguage_C;
3609}
3610
3611extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003612
3613enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3614 if (clang_isDeclaration(cursor.kind))
3615 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3616 if (D->hasAttr<UnavailableAttr>() ||
3617 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3618 return CXAvailability_Available;
3619
3620 if (D->hasAttr<DeprecatedAttr>())
3621 return CXAvailability_Deprecated;
3622 }
3623
3624 return CXAvailability_Available;
3625}
3626
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003627CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3628 if (clang_isDeclaration(cursor.kind))
3629 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3630
3631 return CXLanguage_Invalid;
3632}
3633} // end: extern "C"
3634
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003635
3636//===----------------------------------------------------------------------===//
3637// C++ AST instrospection.
3638//===----------------------------------------------------------------------===//
3639
3640extern "C" {
3641unsigned clang_CXXMethod_isStatic(CXCursor C) {
3642 if (!clang_isDeclaration(C.kind))
3643 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003644
3645 CXXMethodDecl *Method = 0;
3646 Decl *D = cxcursor::getCursorDecl(C);
3647 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3648 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3649 else
3650 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3651 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003652}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003653
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003654} // end: extern "C"
3655
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003656//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003657// Attribute introspection.
3658//===----------------------------------------------------------------------===//
3659
3660extern "C" {
3661CXType clang_getIBOutletCollectionType(CXCursor C) {
3662 if (C.kind != CXCursor_IBOutletCollectionAttr)
3663 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3664
3665 IBOutletCollectionAttr *A =
3666 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3667
3668 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3669}
3670} // end: extern "C"
3671
3672//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003673// CXString Operations.
3674//===----------------------------------------------------------------------===//
3675
3676extern "C" {
3677const char *clang_getCString(CXString string) {
3678 return string.Spelling;
3679}
3680
3681void clang_disposeString(CXString string) {
3682 if (string.MustFreeString && string.Spelling)
3683 free((void*)string.Spelling);
3684}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003685
Ted Kremenekfb480492010-01-13 21:46:36 +00003686} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003687
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003688namespace clang { namespace cxstring {
3689CXString createCXString(const char *String, bool DupString){
3690 CXString Str;
3691 if (DupString) {
3692 Str.Spelling = strdup(String);
3693 Str.MustFreeString = 1;
3694 } else {
3695 Str.Spelling = String;
3696 Str.MustFreeString = 0;
3697 }
3698 return Str;
3699}
3700
3701CXString createCXString(llvm::StringRef String, bool DupString) {
3702 CXString Result;
3703 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3704 char *Spelling = (char *)malloc(String.size() + 1);
3705 memmove(Spelling, String.data(), String.size());
3706 Spelling[String.size()] = 0;
3707 Result.Spelling = Spelling;
3708 Result.MustFreeString = 1;
3709 } else {
3710 Result.Spelling = String.data();
3711 Result.MustFreeString = 0;
3712 }
3713 return Result;
3714}
3715}}
3716
Ted Kremenek04bb7162010-01-22 22:44:15 +00003717//===----------------------------------------------------------------------===//
3718// Misc. utility functions.
3719//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003720
Ted Kremenek04bb7162010-01-22 22:44:15 +00003721extern "C" {
3722
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003723CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003724 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003725}
3726
3727} // end: extern "C"