blob: d75853b65d27ab15b1049deff75bf62d71e6f99e [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);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000395 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000396};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000397
Ted Kremenekab188932010-01-05 19:32:54 +0000398} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000399
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000400static SourceRange getRawCursorExtent(CXCursor C);
401
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000402RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000403 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
404}
405
Douglas Gregorb1373d02010-01-20 20:59:29 +0000406/// \brief Visit the given cursor and, if requested by the visitor,
407/// its children.
408///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000409/// \param Cursor the cursor to visit.
410///
411/// \param CheckRegionOfInterest if true, then the caller already checked that
412/// this cursor is within the region of interest.
413///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000414/// \returns true if the visitation should be aborted, false if it
415/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000416bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000417 if (clang_isInvalid(Cursor.kind))
418 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000419
Douglas Gregorb1373d02010-01-20 20:59:29 +0000420 if (clang_isDeclaration(Cursor.kind)) {
421 Decl *D = getCursorDecl(Cursor);
422 assert(D && "Invalid declaration cursor");
423 if (D->getPCHLevel() > MaxPCHLevel)
424 return false;
425
426 if (D->isImplicit())
427 return false;
428 }
429
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000430 // If we have a range of interest, and this cursor doesn't intersect with it,
431 // we're done.
432 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000433 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000434 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000435 return false;
436 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000437
Douglas Gregorb1373d02010-01-20 20:59:29 +0000438 switch (Visitor(Cursor, Parent, ClientData)) {
439 case CXChildVisit_Break:
440 return true;
441
442 case CXChildVisit_Continue:
443 return false;
444
445 case CXChildVisit_Recurse:
446 return VisitChildren(Cursor);
447 }
448
Douglas Gregorfd643772010-01-25 16:45:46 +0000449 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000450}
451
Douglas Gregor788f5a12010-03-20 00:41:21 +0000452std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
453CursorVisitor::getPreprocessedEntities() {
454 PreprocessingRecord &PPRec
455 = *TU->getPreprocessor().getPreprocessingRecord();
456
457 bool OnlyLocalDecls
458 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
459
460 // There is no region of interest; we have to walk everything.
461 if (RegionOfInterest.isInvalid())
462 return std::make_pair(PPRec.begin(OnlyLocalDecls),
463 PPRec.end(OnlyLocalDecls));
464
465 // Find the file in which the region of interest lands.
466 SourceManager &SM = TU->getSourceManager();
467 std::pair<FileID, unsigned> Begin
468 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
469 std::pair<FileID, unsigned> End
470 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
471
472 // The region of interest spans files; we have to walk everything.
473 if (Begin.first != End.first)
474 return std::make_pair(PPRec.begin(OnlyLocalDecls),
475 PPRec.end(OnlyLocalDecls));
476
477 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
478 = TU->getPreprocessedEntitiesByFile();
479 if (ByFileMap.empty()) {
480 // Build the mapping from files to sets of preprocessed entities.
481 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
482 EEnd = PPRec.end(OnlyLocalDecls);
483 E != EEnd; ++E) {
484 std::pair<FileID, unsigned> P
485 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
486 ByFileMap[P.first].push_back(*E);
487 }
488 }
489
490 return std::make_pair(ByFileMap[Begin.first].begin(),
491 ByFileMap[Begin.first].end());
492}
493
Douglas Gregorb1373d02010-01-20 20:59:29 +0000494/// \brief Visit the children of the given cursor.
495///
496/// \returns true if the visitation should be aborted, false if it
497/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000498bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000499 if (clang_isReference(Cursor.kind)) {
500 // By definition, references have no children.
501 return false;
502 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000503
504 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000505 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000506 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000507
Douglas Gregorb1373d02010-01-20 20:59:29 +0000508 if (clang_isDeclaration(Cursor.kind)) {
509 Decl *D = getCursorDecl(Cursor);
510 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000511 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000512 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000513
Douglas Gregora59e3902010-01-21 23:27:09 +0000514 if (clang_isStatement(Cursor.kind))
515 return Visit(getCursorStmt(Cursor));
516 if (clang_isExpression(Cursor.kind))
517 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000518
Douglas Gregorb1373d02010-01-20 20:59:29 +0000519 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000520 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000521 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
522 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000523 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
524 TLEnd = CXXUnit->top_level_end();
525 TL != TLEnd; ++TL) {
526 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000527 return true;
528 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000529 } else if (VisitDeclContext(
530 CXXUnit->getASTContext().getTranslationUnitDecl()))
531 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000532
Douglas Gregor0396f462010-03-19 05:22:59 +0000533 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000534 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000535 // FIXME: Once we have the ability to deserialize a preprocessing record,
536 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000537 PreprocessingRecord::iterator E, EEnd;
538 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000539 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
540 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
541 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000542
Douglas Gregor0396f462010-03-19 05:22:59 +0000543 continue;
544 }
545
546 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
547 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
548 return true;
549
550 continue;
551 }
552 }
553 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000554 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000555 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000556
Douglas Gregorb1373d02010-01-20 20:59:29 +0000557 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000558 return false;
559}
560
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000561bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000562 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
563 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000564
Ted Kremenek664cffd2010-07-22 11:30:19 +0000565 if (Stmt *Body = B->getBody())
566 return Visit(MakeCXCursor(Body, StmtParent, TU));
567
568 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000569}
570
Douglas Gregorb1373d02010-01-20 20:59:29 +0000571bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000572 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000573 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000574
Ted Kremenek23173d72010-05-18 21:09:07 +0000575 Decl *D = *I;
576 if (D->getLexicalDeclContext() != DC)
577 continue;
578
579 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000580
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000581 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000582 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000583 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000584 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000585
586 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000587 case RangeBefore:
588 // This declaration comes before the region of interest; skip it.
589 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000590
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000591 case RangeAfter:
592 // This declaration comes after the region of interest; we're done.
593 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000594
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000595 case RangeOverlap:
596 // This declaration overlaps the region of interest; visit it.
597 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000598 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000599 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000600
Daniel Dunbard52864b2010-02-14 10:02:57 +0000601 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000602 return true;
603 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000604
Douglas Gregorb1373d02010-01-20 20:59:29 +0000605 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000606}
607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
609 llvm_unreachable("Translation units are visited directly by Visit()");
610 return false;
611}
612
613bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
614 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
615 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000616
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000617 return false;
618}
619
620bool CursorVisitor::VisitTagDecl(TagDecl *D) {
621 return VisitDeclContext(D);
622}
623
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000624bool CursorVisitor::VisitClassTemplateSpecializationDecl(
625 ClassTemplateSpecializationDecl *D) {
626 bool ShouldVisitBody = false;
627 switch (D->getSpecializationKind()) {
628 case TSK_Undeclared:
629 case TSK_ImplicitInstantiation:
630 // Nothing to visit
631 return false;
632
633 case TSK_ExplicitInstantiationDeclaration:
634 case TSK_ExplicitInstantiationDefinition:
635 break;
636
637 case TSK_ExplicitSpecialization:
638 ShouldVisitBody = true;
639 break;
640 }
641
642 // Visit the template arguments used in the specialization.
643 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
644 TypeLoc TL = SpecType->getTypeLoc();
645 if (TemplateSpecializationTypeLoc *TSTLoc
646 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
647 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
648 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
649 return true;
650 }
651 }
652
653 if (ShouldVisitBody && VisitCXXRecordDecl(D))
654 return true;
655
656 return false;
657}
658
Douglas Gregor74dbe642010-08-31 19:31:58 +0000659bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
660 ClassTemplatePartialSpecializationDecl *D) {
661 // FIXME: Visit the "outer" template parameter lists on the TagDecl
662 // before visiting these template parameters.
663 if (VisitTemplateParameters(D->getTemplateParameters()))
664 return true;
665
666 // Visit the partial specialization arguments.
667 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
668 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
669 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
670 return true;
671
672 return VisitCXXRecordDecl(D);
673}
674
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000675bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000676 // Visit the default argument.
677 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
678 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
679 if (Visit(DefArg->getTypeLoc()))
680 return true;
681
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000682 return false;
683}
684
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000685bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
686 if (Expr *Init = D->getInitExpr())
687 return Visit(MakeCXCursor(Init, StmtParent, TU));
688 return false;
689}
690
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000691bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
692 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
693 if (Visit(TSInfo->getTypeLoc()))
694 return true;
695
696 return false;
697}
698
Douglas Gregorb1373d02010-01-20 20:59:29 +0000699bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000700 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
701 // Visit the function declaration's syntactic components in the order
702 // written. This requires a bit of work.
703 TypeLoc TL = TSInfo->getTypeLoc();
704 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
705
706 // If we have a function declared directly (without the use of a typedef),
707 // visit just the return type. Otherwise, just visit the function's type
708 // now.
709 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
710 (!FTL && Visit(TL)))
711 return true;
712
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000713 // Visit the nested-name-specifier, if present.
714 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
715 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
716 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000717
718 // Visit the declaration name.
719 if (VisitDeclarationNameInfo(ND->getNameInfo()))
720 return true;
721
722 // FIXME: Visit explicitly-specified template arguments!
723
724 // Visit the function parameters, if we have a function type.
725 if (FTL && VisitFunctionTypeLoc(*FTL, true))
726 return true;
727
728 // FIXME: Attributes?
729 }
730
Douglas Gregora59e3902010-01-21 23:27:09 +0000731 if (ND->isThisDeclarationADefinition() &&
732 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
733 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000734
Douglas Gregorb1373d02010-01-20 20:59:29 +0000735 return false;
736}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000737
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000738bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
739 if (VisitDeclaratorDecl(D))
740 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000741
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000742 if (Expr *BitWidth = D->getBitWidth())
743 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000744
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000745 return false;
746}
747
748bool CursorVisitor::VisitVarDecl(VarDecl *D) {
749 if (VisitDeclaratorDecl(D))
750 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000751
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000752 if (Expr *Init = D->getInit())
753 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000754
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000755 return false;
756}
757
Douglas Gregor84b51d72010-09-01 20:16:53 +0000758bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
759 if (VisitDeclaratorDecl(D))
760 return true;
761
762 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
763 if (Expr *DefArg = D->getDefaultArgument())
764 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
765
766 return false;
767}
768
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000769bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
770 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
771 // before visiting these template parameters.
772 if (VisitTemplateParameters(D->getTemplateParameters()))
773 return true;
774
775 return VisitFunctionDecl(D->getTemplatedDecl());
776}
777
Douglas Gregor39d6f072010-08-31 19:02:00 +0000778bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
779 // FIXME: Visit the "outer" template parameter lists on the TagDecl
780 // before visiting these template parameters.
781 if (VisitTemplateParameters(D->getTemplateParameters()))
782 return true;
783
784 return VisitCXXRecordDecl(D->getTemplatedDecl());
785}
786
Douglas Gregor84b51d72010-09-01 20:16:53 +0000787bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
788 if (VisitTemplateParameters(D->getTemplateParameters()))
789 return true;
790
791 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
792 VisitTemplateArgumentLoc(D->getDefaultArgument()))
793 return true;
794
795 return false;
796}
797
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000798bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000799 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
800 if (Visit(TSInfo->getTypeLoc()))
801 return true;
802
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000803 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000804 PEnd = ND->param_end();
805 P != PEnd; ++P) {
806 if (Visit(MakeCXCursor(*P, TU)))
807 return true;
808 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000809
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000810 if (ND->isThisDeclarationADefinition() &&
811 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
812 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000813
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000814 return false;
815}
816
Douglas Gregora59e3902010-01-21 23:27:09 +0000817bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
818 return VisitDeclContext(D);
819}
820
Douglas Gregorb1373d02010-01-20 20:59:29 +0000821bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000822 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
823 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000824 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000825
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000826 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
827 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
828 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000829 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000830 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000831
Douglas Gregora59e3902010-01-21 23:27:09 +0000832 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000833}
834
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000835bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
836 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
837 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
838 E = PID->protocol_end(); I != E; ++I, ++PL)
839 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
840 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000841
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842 return VisitObjCContainerDecl(PID);
843}
844
Ted Kremenek23173d72010-05-18 21:09:07 +0000845bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000846 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
847 return true;
848
Ted Kremenek23173d72010-05-18 21:09:07 +0000849 // FIXME: This implements a workaround with @property declarations also being
850 // installed in the DeclContext for the @interface. Eventually this code
851 // should be removed.
852 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
853 if (!CDecl || !CDecl->IsClassExtension())
854 return false;
855
856 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
857 if (!ID)
858 return false;
859
860 IdentifierInfo *PropertyId = PD->getIdentifier();
861 ObjCPropertyDecl *prevDecl =
862 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
863
864 if (!prevDecl)
865 return false;
866
867 // Visit synthesized methods since they will be skipped when visiting
868 // the @interface.
869 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
870 if (MD->isSynthesized())
871 if (Visit(MakeCXCursor(MD, TU)))
872 return true;
873
874 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
875 if (MD->isSynthesized())
876 if (Visit(MakeCXCursor(MD, TU)))
877 return true;
878
879 return false;
880}
881
Douglas Gregorb1373d02010-01-20 20:59:29 +0000882bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000883 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000884 if (D->getSuperClass() &&
885 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000886 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000887 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000888 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000889
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000890 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
891 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
892 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000893 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000894 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000895
Douglas Gregora59e3902010-01-21 23:27:09 +0000896 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000897}
898
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000899bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
900 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000901}
902
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000903bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000904 // 'ID' could be null when dealing with invalid code.
905 if (ObjCInterfaceDecl *ID = D->getClassInterface())
906 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
907 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000908
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000909 return VisitObjCImplDecl(D);
910}
911
912bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
913#if 0
914 // Issue callbacks for super class.
915 // FIXME: No source location information!
916 if (D->getSuperClass() &&
917 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000918 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000919 TU)))
920 return true;
921#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000922
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000923 return VisitObjCImplDecl(D);
924}
925
926bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
927 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
928 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
929 E = D->protocol_end();
930 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000931 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000932 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000933
934 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000935}
936
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000937bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
938 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
939 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
940 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000941
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000942 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000943}
944
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000945bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
946 return VisitDeclContext(D);
947}
948
Douglas Gregor69319002010-08-31 23:48:11 +0000949bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000950 // Visit nested-name-specifier.
951 if (NestedNameSpecifier *Qualifier = D->getQualifier())
952 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
953 return true;
Douglas Gregor69319002010-08-31 23:48:11 +0000954
955 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
956 D->getTargetNameLoc(), TU));
957}
958
Douglas Gregor7e242562010-09-01 19:52:22 +0000959bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000960 // Visit nested-name-specifier.
961 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
962 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
963 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +0000964
965 // FIXME: Provide a multi-reference of some kind for all of the declarations
966 // that the using declaration refers to. We don't have this kind of cursor
967 // yet.
968
969 return VisitDeclarationNameInfo(D->getNameInfo());
970}
971
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000972bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000973 // Visit nested-name-specifier.
974 if (NestedNameSpecifier *Qualifier = D->getQualifier())
975 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
976 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000977
978 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
979 D->getIdentLocation(), TU));
980}
981
Douglas Gregor7e242562010-09-01 19:52:22 +0000982bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000983 // Visit nested-name-specifier.
984 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
985 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
986 return true;
987
Douglas Gregor7e242562010-09-01 19:52:22 +0000988 return VisitDeclarationNameInfo(D->getNameInfo());
989}
990
991bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
992 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000993 // Visit nested-name-specifier.
994 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
995 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
996 return true;
997
Douglas Gregor7e242562010-09-01 19:52:22 +0000998 return false;
999}
1000
Douglas Gregor01829d32010-08-31 14:41:23 +00001001bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1002 switch (Name.getName().getNameKind()) {
1003 case clang::DeclarationName::Identifier:
1004 case clang::DeclarationName::CXXLiteralOperatorName:
1005 case clang::DeclarationName::CXXOperatorName:
1006 case clang::DeclarationName::CXXUsingDirective:
1007 return false;
1008
1009 case clang::DeclarationName::CXXConstructorName:
1010 case clang::DeclarationName::CXXDestructorName:
1011 case clang::DeclarationName::CXXConversionFunctionName:
1012 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1013 return Visit(TSInfo->getTypeLoc());
1014 return false;
1015
1016 case clang::DeclarationName::ObjCZeroArgSelector:
1017 case clang::DeclarationName::ObjCOneArgSelector:
1018 case clang::DeclarationName::ObjCMultiArgSelector:
1019 // FIXME: Per-identifier location info?
1020 return false;
1021 }
1022
1023 return false;
1024}
1025
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001026bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1027 SourceRange Range) {
1028 // FIXME: This whole routine is a hack to work around the lack of proper
1029 // source information in nested-name-specifiers (PR5791). Since we do have
1030 // a beginning source location, we can visit the first component of the
1031 // nested-name-specifier, if it's a single-token component.
1032 if (!NNS)
1033 return false;
1034
1035 // Get the first component in the nested-name-specifier.
1036 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1037 NNS = Prefix;
1038
1039 switch (NNS->getKind()) {
1040 case NestedNameSpecifier::Namespace:
1041 // FIXME: The token at this source location might actually have been a
1042 // namespace alias, but we don't model that. Lame!
1043 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1044 TU));
1045
1046 case NestedNameSpecifier::TypeSpec: {
1047 // If the type has a form where we know that the beginning of the source
1048 // range matches up with a reference cursor. Visit the appropriate reference
1049 // cursor.
1050 Type *T = NNS->getAsType();
1051 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1052 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1053 if (const TagType *Tag = dyn_cast<TagType>(T))
1054 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1055 if (const TemplateSpecializationType *TST
1056 = dyn_cast<TemplateSpecializationType>(T))
1057 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1058 break;
1059 }
1060
1061 case NestedNameSpecifier::TypeSpecWithTemplate:
1062 case NestedNameSpecifier::Global:
1063 case NestedNameSpecifier::Identifier:
1064 break;
1065 }
1066
1067 return false;
1068}
1069
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001070bool CursorVisitor::VisitTemplateParameters(
1071 const TemplateParameterList *Params) {
1072 if (!Params)
1073 return false;
1074
1075 for (TemplateParameterList::const_iterator P = Params->begin(),
1076 PEnd = Params->end();
1077 P != PEnd; ++P) {
1078 if (Visit(MakeCXCursor(*P, TU)))
1079 return true;
1080 }
1081
1082 return false;
1083}
1084
Douglas Gregor0b36e612010-08-31 20:37:03 +00001085bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1086 switch (Name.getKind()) {
1087 case TemplateName::Template:
1088 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1089
1090 case TemplateName::OverloadedTemplate:
1091 // FIXME: We need a way to return multiple lookup results in a single
1092 // cursor.
1093 return false;
1094
1095 case TemplateName::DependentTemplate:
1096 // FIXME: Visit nested-name-specifier.
1097 return false;
1098
1099 case TemplateName::QualifiedTemplate:
1100 // FIXME: Visit nested-name-specifier.
1101 return Visit(MakeCursorTemplateRef(
1102 Name.getAsQualifiedTemplateName()->getDecl(),
1103 Loc, TU));
1104 }
1105
1106 return false;
1107}
1108
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001109bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1110 switch (TAL.getArgument().getKind()) {
1111 case TemplateArgument::Null:
1112 case TemplateArgument::Integral:
1113 return false;
1114
1115 case TemplateArgument::Pack:
1116 // FIXME: Implement when variadic templates come along.
1117 return false;
1118
1119 case TemplateArgument::Type:
1120 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1121 return Visit(TSInfo->getTypeLoc());
1122 return false;
1123
1124 case TemplateArgument::Declaration:
1125 if (Expr *E = TAL.getSourceDeclExpression())
1126 return Visit(MakeCXCursor(E, StmtParent, TU));
1127 return false;
1128
1129 case TemplateArgument::Expression:
1130 if (Expr *E = TAL.getSourceExpression())
1131 return Visit(MakeCXCursor(E, StmtParent, TU));
1132 return false;
1133
1134 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001135 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1136 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001137 }
1138
1139 return false;
1140}
1141
Ted Kremeneka0536d82010-05-07 01:04:29 +00001142bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1143 return VisitDeclContext(D);
1144}
1145
Douglas Gregor01829d32010-08-31 14:41:23 +00001146bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1147 return Visit(TL.getUnqualifiedLoc());
1148}
1149
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001150bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1151 ASTContext &Context = TU->getASTContext();
1152
1153 // Some builtin types (such as Objective-C's "id", "sel", and
1154 // "Class") have associated declarations. Create cursors for those.
1155 QualType VisitType;
1156 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001157 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001158 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001159 case BuiltinType::Char_U:
1160 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001161 case BuiltinType::Char16:
1162 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001163 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001164 case BuiltinType::UInt:
1165 case BuiltinType::ULong:
1166 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001167 case BuiltinType::UInt128:
1168 case BuiltinType::Char_S:
1169 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001170 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001171 case BuiltinType::Short:
1172 case BuiltinType::Int:
1173 case BuiltinType::Long:
1174 case BuiltinType::LongLong:
1175 case BuiltinType::Int128:
1176 case BuiltinType::Float:
1177 case BuiltinType::Double:
1178 case BuiltinType::LongDouble:
1179 case BuiltinType::NullPtr:
1180 case BuiltinType::Overload:
1181 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001182 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001183
1184 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001185 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001186
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001187 case BuiltinType::ObjCId:
1188 VisitType = Context.getObjCIdType();
1189 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001190
1191 case BuiltinType::ObjCClass:
1192 VisitType = Context.getObjCClassType();
1193 break;
1194
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001195 case BuiltinType::ObjCSel:
1196 VisitType = Context.getObjCSelType();
1197 break;
1198 }
1199
1200 if (!VisitType.isNull()) {
1201 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001202 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001203 TU));
1204 }
1205
1206 return false;
1207}
1208
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001209bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1210 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1211}
1212
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001213bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1214 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1215}
1216
1217bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1218 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1219}
1220
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001221bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1222 // FIXME: We can't visit the template template parameter, but there's
1223 // no context information with which we can match up the depth/index in the
1224 // type to the appropriate
1225 return false;
1226}
1227
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001228bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1229 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1230 return true;
1231
John McCallc12c5bb2010-05-15 11:32:37 +00001232 return false;
1233}
1234
1235bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1236 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1237 return true;
1238
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001239 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1240 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1241 TU)))
1242 return true;
1243 }
1244
1245 return false;
1246}
1247
1248bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001249 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001250}
1251
1252bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1253 return Visit(TL.getPointeeLoc());
1254}
1255
1256bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1257 return Visit(TL.getPointeeLoc());
1258}
1259
1260bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1261 return Visit(TL.getPointeeLoc());
1262}
1263
1264bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001265 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001266}
1267
1268bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001269 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001270}
1271
Douglas Gregor01829d32010-08-31 14:41:23 +00001272bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1273 bool SkipResultType) {
1274 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001275 return true;
1276
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001277 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001278 if (Decl *D = TL.getArg(I))
1279 if (Visit(MakeCXCursor(D, TU)))
1280 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001281
1282 return false;
1283}
1284
1285bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1286 if (Visit(TL.getElementLoc()))
1287 return true;
1288
1289 if (Expr *Size = TL.getSizeExpr())
1290 return Visit(MakeCXCursor(Size, StmtParent, TU));
1291
1292 return false;
1293}
1294
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001295bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1296 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001297 // Visit the template name.
1298 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1299 TL.getTemplateNameLoc()))
1300 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001301
1302 // Visit the template arguments.
1303 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1304 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1305 return true;
1306
1307 return false;
1308}
1309
Douglas Gregor2332c112010-01-21 20:48:56 +00001310bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1311 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1312}
1313
1314bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1315 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1316 return Visit(TSInfo->getTypeLoc());
1317
1318 return false;
1319}
1320
Douglas Gregora59e3902010-01-21 23:27:09 +00001321bool CursorVisitor::VisitStmt(Stmt *S) {
1322 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1323 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001324 if (Stmt *C = *Child)
1325 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1326 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001327 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001328
Douglas Gregora59e3902010-01-21 23:27:09 +00001329 return false;
1330}
1331
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001332bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1333 // Specially handle CaseStmts because they can be nested, e.g.:
1334 //
1335 // case 1:
1336 // case 2:
1337 //
1338 // In this case the second CaseStmt is the child of the first. Walking
1339 // these recursively can blow out the stack.
1340 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1341 while (true) {
1342 // Set the Parent field to Cursor, then back to its old value once we're
1343 // done.
1344 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1345
1346 if (Stmt *LHS = S->getLHS())
1347 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1348 return true;
1349 if (Stmt *RHS = S->getRHS())
1350 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1351 return true;
1352 if (Stmt *SubStmt = S->getSubStmt()) {
1353 if (!isa<CaseStmt>(SubStmt))
1354 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1355
1356 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1357 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1358 Cursor = MakeCXCursor(CS, StmtParent, TU);
1359 if (RegionOfInterest.isValid()) {
1360 SourceRange Range = CS->getSourceRange();
1361 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1362 return false;
1363 }
1364
1365 switch (Visitor(Cursor, Parent, ClientData)) {
1366 case CXChildVisit_Break: return true;
1367 case CXChildVisit_Continue: return false;
1368 case CXChildVisit_Recurse:
1369 // Perform tail-recursion manually.
1370 S = CS;
1371 continue;
1372 }
1373 }
1374 return false;
1375 }
1376}
1377
Douglas Gregora59e3902010-01-21 23:27:09 +00001378bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1379 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1380 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001381 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001382 return true;
1383 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001384
Douglas Gregora59e3902010-01-21 23:27:09 +00001385 return false;
1386}
1387
Douglas Gregorf5bab412010-01-22 01:00:11 +00001388bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1389 if (VarDecl *Var = S->getConditionVariable()) {
1390 if (Visit(MakeCXCursor(Var, TU)))
1391 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001392 }
1393
Douglas Gregor263b47b2010-01-25 16:12:32 +00001394 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1395 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001396 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1397 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001398 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1399 return true;
1400
1401 return false;
1402}
1403
1404bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1405 if (VarDecl *Var = S->getConditionVariable()) {
1406 if (Visit(MakeCXCursor(Var, TU)))
1407 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001408 }
1409
Douglas Gregor263b47b2010-01-25 16:12:32 +00001410 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1411 return true;
1412 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1413 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001414
Douglas Gregor263b47b2010-01-25 16:12:32 +00001415 return false;
1416}
1417
1418bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1419 if (VarDecl *Var = S->getConditionVariable()) {
1420 if (Visit(MakeCXCursor(Var, TU)))
1421 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001422 }
1423
Douglas Gregor263b47b2010-01-25 16:12:32 +00001424 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1425 return true;
1426 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001427 return true;
1428
Douglas Gregor263b47b2010-01-25 16:12:32 +00001429 return false;
1430}
1431
1432bool CursorVisitor::VisitForStmt(ForStmt *S) {
1433 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1434 return true;
1435 if (VarDecl *Var = S->getConditionVariable()) {
1436 if (Visit(MakeCXCursor(Var, TU)))
1437 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001438 }
1439
Douglas Gregor263b47b2010-01-25 16:12:32 +00001440 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1441 return true;
1442 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1443 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001444 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1445 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001446
Douglas Gregorf5bab412010-01-22 01:00:11 +00001447 return false;
1448}
1449
Douglas Gregor8947a752010-09-02 20:35:02 +00001450bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1451 // Visit nested-name-specifier, if present.
1452 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1453 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1454 return true;
1455
1456 // Visit declaration name.
1457 if (VisitDeclarationNameInfo(E->getNameInfo()))
1458 return true;
1459
1460 // Visit explicitly-specified template arguments.
1461 if (E->hasExplicitTemplateArgs()) {
1462 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1463 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1464 *ArgEnd = Arg + Args.NumTemplateArgs;
1465 Arg != ArgEnd; ++Arg)
1466 if (VisitTemplateArgumentLoc(*Arg))
1467 return true;
1468 }
1469
1470 return false;
1471}
1472
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001473bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1474 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1475 return true;
1476
1477 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1478 return true;
1479
1480 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1481 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1482 return true;
1483
1484 return false;
1485}
1486
Ted Kremenek3064ef92010-08-27 21:34:58 +00001487bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1488 if (D->isDefinition()) {
1489 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1490 E = D->bases_end(); I != E; ++I) {
1491 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1492 return true;
1493 }
1494 }
1495
1496 return VisitTagDecl(D);
1497}
1498
1499
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001500bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1501 return Visit(B->getBlockDecl());
1502}
1503
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001504bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1505 // FIXME: Visit fields as well?
1506 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1507 return true;
1508
1509 return VisitExpr(E);
1510}
1511
Douglas Gregor336fd812010-01-23 00:40:08 +00001512bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1513 if (E->isArgumentType()) {
1514 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1515 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001516
Douglas Gregor336fd812010-01-23 00:40:08 +00001517 return false;
1518 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001519
Douglas Gregor336fd812010-01-23 00:40:08 +00001520 return VisitExpr(E);
1521}
1522
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001523bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1524 // Visit the base expression.
1525 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1526 return true;
1527
1528 // Visit the nested-name-specifier
1529 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1530 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1531 return true;
1532
1533 // Visit the declaration name.
1534 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1535 return true;
1536
1537 // Visit the explicitly-specified template arguments, if any.
1538 if (E->hasExplicitTemplateArgs()) {
1539 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1540 *ArgEnd = Arg + E->getNumTemplateArgs();
1541 Arg != ArgEnd;
1542 ++Arg) {
1543 if (VisitTemplateArgumentLoc(*Arg))
1544 return true;
1545 }
1546 }
1547
1548 return false;
1549}
1550
Douglas Gregor336fd812010-01-23 00:40:08 +00001551bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1552 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1553 if (Visit(TSInfo->getTypeLoc()))
1554 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001555
Douglas Gregor336fd812010-01-23 00:40:08 +00001556 return VisitCastExpr(E);
1557}
1558
1559bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1560 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1561 if (Visit(TSInfo->getTypeLoc()))
1562 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001563
Douglas Gregor336fd812010-01-23 00:40:08 +00001564 return VisitExpr(E);
1565}
1566
Douglas Gregor648220e2010-08-10 15:02:34 +00001567bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1568 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1569 Visit(E->getArgTInfo2()->getTypeLoc());
1570}
1571
1572bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1573 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1574 return true;
1575
1576 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1577}
1578
Douglas Gregor94802292010-09-02 21:20:16 +00001579bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1580 if (E->isTypeOperand()) {
1581 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1582 return Visit(TSInfo->getTypeLoc());
1583
1584 return false;
1585 }
1586
1587 return VisitExpr(E);
1588}
1589
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001590bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1591 // Visit base expression.
1592 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1593 return true;
1594
1595 // Visit the nested-name-specifier.
1596 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1597 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1598 return true;
1599
1600 // Visit the scope type that looks disturbingly like the nested-name-specifier
1601 // but isn't.
1602 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1603 if (Visit(TSInfo->getTypeLoc()))
1604 return true;
1605
1606 // Visit the name of the type being destroyed.
1607 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1608 if (Visit(TSInfo->getTypeLoc()))
1609 return true;
1610
1611 return false;
1612}
1613
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001614bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001615 // Visit the nested-name-specifier.
1616 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1617 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1618 return true;
1619
1620 // Visit the declaration name.
1621 if (VisitDeclarationNameInfo(E->getNameInfo()))
1622 return true;
1623
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001624 // Visit the explicitly-specified template arguments.
1625 if (const ExplicitTemplateArgumentList *ArgList
1626 = E->getOptionalExplicitTemplateArgs()) {
1627 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1628 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1629 Arg != ArgEnd; ++Arg) {
1630 if (VisitTemplateArgumentLoc(*Arg))
1631 return true;
1632 }
1633 }
1634
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001635 // FIXME: We don't have a way to visit all of the declarations referenced
1636 // here.
1637 return false;
1638}
1639
Douglas Gregorbfebed22010-09-03 17:24:10 +00001640bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1641 DependentScopeDeclRefExpr *E) {
1642 // Visit the nested-name-specifier.
1643 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1644 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1645 return true;
1646
1647 // Visit the declaration name.
1648 if (VisitDeclarationNameInfo(E->getNameInfo()))
1649 return true;
1650
1651 // Visit the explicitly-specified template arguments.
1652 if (const ExplicitTemplateArgumentList *ArgList
1653 = E->getOptionalExplicitTemplateArgs()) {
1654 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1655 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1656 Arg != ArgEnd; ++Arg) {
1657 if (VisitTemplateArgumentLoc(*Arg))
1658 return true;
1659 }
1660 }
1661
1662 return false;
1663}
1664
Douglas Gregorc2350e52010-03-08 16:40:19 +00001665bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001666 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1667 if (Visit(TSInfo->getTypeLoc()))
1668 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001669
1670 return VisitExpr(E);
1671}
1672
Douglas Gregor81d34662010-04-20 15:39:42 +00001673bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1674 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1675}
1676
1677
Ted Kremenek09dfa372010-02-18 05:46:33 +00001678bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001679 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1680 i != e; ++i)
1681 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001682 return true;
1683
1684 return false;
1685}
1686
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001687extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001688CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1689 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001690 // We use crash recovery to make some of our APIs more reliable, implicitly
1691 // enable it.
1692 llvm::CrashRecoveryContext::Enable();
1693
Douglas Gregora030b7c2010-01-22 20:35:53 +00001694 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001695 if (excludeDeclarationsFromPCH)
1696 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001697 if (displayDiagnostics)
1698 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001699 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001700}
1701
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001702void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001703 if (CIdx)
1704 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001705 if (getenv("LIBCLANG_TIMING"))
1706 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001707}
1708
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001709void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001710 if (CIdx) {
1711 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1712 CXXIdx->setUseExternalASTGeneration(value);
1713 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001714}
1715
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001716CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001717 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001718 if (!CIdx)
1719 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001720
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001721 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001722
Douglas Gregor28019772010-04-05 23:52:57 +00001723 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001724 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001725 CXXIdx->getOnlyLocalDecls(),
1726 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001727}
1728
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001729unsigned clang_defaultEditingTranslationUnitOptions() {
1730 return CXTranslationUnit_PrecompiledPreamble;
1731}
1732
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001733CXTranslationUnit
1734clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1735 const char *source_filename,
1736 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001737 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001738 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001739 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001740 return clang_parseTranslationUnit(CIdx, source_filename,
1741 command_line_args, num_command_line_args,
1742 unsaved_files, num_unsaved_files,
1743 CXTranslationUnit_DetailedPreprocessingRecord);
1744}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001745
1746struct ParseTranslationUnitInfo {
1747 CXIndex CIdx;
1748 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001749 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001750 int num_command_line_args;
1751 struct CXUnsavedFile *unsaved_files;
1752 unsigned num_unsaved_files;
1753 unsigned options;
1754 CXTranslationUnit result;
1755};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001756static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001757 ParseTranslationUnitInfo *PTUI =
1758 static_cast<ParseTranslationUnitInfo*>(UserData);
1759 CXIndex CIdx = PTUI->CIdx;
1760 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001761 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001762 int num_command_line_args = PTUI->num_command_line_args;
1763 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1764 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1765 unsigned options = PTUI->options;
1766 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001767
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001768 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001769 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001770
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001771 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1772
Douglas Gregor44c181a2010-07-23 00:33:23 +00001773 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001774 bool CompleteTranslationUnit
1775 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001776 bool CacheCodeCompetionResults
1777 = options & CXTranslationUnit_CacheCompletionResults;
1778
Douglas Gregor5352ac02010-01-28 00:27:43 +00001779 // Configure the diagnostics.
1780 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001781 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1782 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001783
Douglas Gregor4db64a42010-01-23 00:14:00 +00001784 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1785 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001786 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001787 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001788 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001789 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1790 Buffer));
1791 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001792
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001793 if (!CXXIdx->getUseExternalASTGeneration()) {
1794 llvm::SmallVector<const char *, 16> Args;
1795
1796 // The 'source_filename' argument is optional. If the caller does not
1797 // specify it then it is assumed that the source file is specified
1798 // in the actual argument list.
1799 if (source_filename)
1800 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001801
1802 // Since the Clang C library is primarily used by batch tools dealing with
1803 // (often very broken) source code, where spell-checking can have a
1804 // significant negative impact on performance (particularly when
1805 // precompiled headers are involved), we disable it by default.
1806 // Note that we place this argument early in the list, so that it can be
1807 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001808 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001809
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001810 Args.insert(Args.end(), command_line_args,
1811 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001812
Douglas Gregor44c181a2010-07-23 00:33:23 +00001813 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001814 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1815 Args.push_back("-Xclang");
1816 Args.push_back("-detailed-preprocessing-record");
1817 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001818
Douglas Gregor5352ac02010-01-28 00:27:43 +00001819 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001820
Ted Kremenek29b72842010-01-07 22:49:05 +00001821#ifdef USE_CRASHTRACER
1822 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001823#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001824
Daniel Dunbar94220972009-12-05 02:17:18 +00001825 llvm::OwningPtr<ASTUnit> Unit(
1826 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001827 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001828 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001829 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001830 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001831 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001832 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001833 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001834 CompleteTranslationUnit,
1835 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001836
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001837 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001838 // Make sure to check that 'Unit' is non-NULL.
1839 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001840 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1841 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001842 D != DEnd; ++D) {
1843 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001844 CXString Msg = clang_formatDiagnostic(&Diag,
1845 clang_defaultDiagnosticDisplayOptions());
1846 fprintf(stderr, "%s\n", clang_getCString(Msg));
1847 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001848 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001849#ifdef LLVM_ON_WIN32
1850 // On Windows, force a flush, since there may be multiple copies of
1851 // stderr and stdout in the file system, all with different buffers
1852 // but writing to the same device.
1853 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001854#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001855 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001856 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001857
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001858 PTUI->result = Unit.take();
1859 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001860 }
1861
Ted Kremenek139ba862009-10-22 00:03:57 +00001862 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001863 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001864
Ted Kremenek139ba862009-10-22 00:03:57 +00001865 // First add the complete path to the 'clang' executable.
1866 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001867 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001868
Ted Kremenek139ba862009-10-22 00:03:57 +00001869 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001870 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001871
Ted Kremenek139ba862009-10-22 00:03:57 +00001872 // The 'source_filename' argument is optional. If the caller does not
1873 // specify it then it is assumed that the source file is specified
1874 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001875 if (source_filename)
1876 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001877
Steve Naroff37b5ac22009-10-15 20:50:09 +00001878 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001879 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001880 char astTmpFile[L_tmpnam];
1881 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001882
1883 // Since the Clang C library is primarily used by batch tools dealing with
1884 // (often very broken) source code, where spell-checking can have a
1885 // significant negative impact on performance (particularly when
1886 // precompiled headers are involved), we disable it by default.
1887 // Note that we place this argument early in the list, so that it can be
1888 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001889 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001890
Douglas Gregor4db64a42010-01-23 00:14:00 +00001891 // Remap any unsaved files to temporary files.
1892 std::vector<llvm::sys::Path> TemporaryFiles;
1893 std::vector<std::string> RemapArgs;
1894 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001895 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001896
Douglas Gregor4db64a42010-01-23 00:14:00 +00001897 // The pointers into the elements of RemapArgs are stable because we
1898 // won't be adding anything to RemapArgs after this point.
1899 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1900 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001901
Ted Kremenek139ba862009-10-22 00:03:57 +00001902 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1903 for (int i = 0; i < num_command_line_args; ++i)
1904 if (const char *arg = command_line_args[i]) {
1905 if (strcmp(arg, "-o") == 0) {
1906 ++i; // Also skip the matching argument.
1907 continue;
1908 }
1909 if (strcmp(arg, "-emit-ast") == 0 ||
1910 strcmp(arg, "-c") == 0 ||
1911 strcmp(arg, "-fsyntax-only") == 0) {
1912 continue;
1913 }
1914
1915 // Keep the argument.
1916 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001917 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001918
Douglas Gregord93256e2010-01-28 06:00:51 +00001919 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001920 char tmpFileResults[L_tmpnam];
1921 char *tmpResultsFileName = tmpnam(tmpFileResults);
1922 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001923 TemporaryFiles.push_back(DiagnosticsFile);
1924 argv.push_back("-fdiagnostics-binary");
1925
Douglas Gregor44c181a2010-07-23 00:33:23 +00001926 // Do we need the detailed preprocessing record?
1927 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1928 argv.push_back("-Xclang");
1929 argv.push_back("-detailed-preprocessing-record");
1930 }
1931
Ted Kremenek139ba862009-10-22 00:03:57 +00001932 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001933 argv.push_back(NULL);
1934
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001935 // Invoke 'clang'.
1936 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1937 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001938 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001939 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1940 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001941 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001942 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001943 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001944
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001945 if (!ErrMsg.empty()) {
1946 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001947 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001948 I != E; ++I) {
1949 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001950 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001951 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001952 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001953
Daniel Dunbar32141c82010-02-23 20:23:45 +00001954 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001955 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001956
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001957 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001958 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001959 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001960 RemappedFiles.size(),
1961 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001962 if (ATU) {
1963 LoadSerializedDiagnostics(DiagnosticsFile,
1964 num_unsaved_files, unsaved_files,
1965 ATU->getFileManager(),
1966 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001967 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001968 } else if (CXXIdx->getDisplayDiagnostics()) {
1969 // We failed to load the ASTUnit, but we can still deserialize the
1970 // diagnostics and emit them.
1971 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001972 Diagnostic Diag;
1973 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001974 // FIXME: Faked LangOpts!
1975 LangOptions LangOpts;
1976 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1977 LoadSerializedDiagnostics(DiagnosticsFile,
1978 num_unsaved_files, unsaved_files,
1979 FileMgr, SourceMgr, Diags);
1980 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1981 DEnd = Diags.end();
1982 D != DEnd; ++D) {
1983 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001984 CXString Msg = clang_formatDiagnostic(&Diag,
1985 clang_defaultDiagnosticDisplayOptions());
1986 fprintf(stderr, "%s\n", clang_getCString(Msg));
1987 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001988 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001989
1990#ifdef LLVM_ON_WIN32
1991 // On Windows, force a flush, since there may be multiple copies of
1992 // stderr and stdout in the file system, all with different buffers
1993 // but writing to the same device.
1994 fflush(stderr);
1995#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001996 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001997
Douglas Gregor313e26c2010-02-18 23:35:40 +00001998 if (ATU) {
1999 // Make the translation unit responsible for destroying all temporary files.
2000 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2001 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002002 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00002003 } else {
2004 // Destroy all of the temporary files now; they can't be referenced any
2005 // longer.
2006 llvm::sys::Path(astTmpFile).eraseFromDisk();
2007 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2008 TemporaryFiles[i].eraseFromDisk();
2009 }
2010
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002011 PTUI->result = ATU;
2012}
2013CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2014 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002015 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002016 int num_command_line_args,
2017 struct CXUnsavedFile *unsaved_files,
2018 unsigned num_unsaved_files,
2019 unsigned options) {
2020 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2021 num_command_line_args, unsaved_files, num_unsaved_files,
2022 options, 0 };
2023 llvm::CrashRecoveryContext CRC;
2024
2025 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002026 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2027 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2028 fprintf(stderr, " 'command_line_args' : [");
2029 for (int i = 0; i != num_command_line_args; ++i) {
2030 if (i)
2031 fprintf(stderr, ", ");
2032 fprintf(stderr, "'%s'", command_line_args[i]);
2033 }
2034 fprintf(stderr, "],\n");
2035 fprintf(stderr, " 'unsaved_files' : [");
2036 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2037 if (i)
2038 fprintf(stderr, ", ");
2039 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2040 unsaved_files[i].Length);
2041 }
2042 fprintf(stderr, "],\n");
2043 fprintf(stderr, " 'options' : %d,\n", options);
2044 fprintf(stderr, "}\n");
2045
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002046 return 0;
2047 }
2048
2049 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002050}
2051
Douglas Gregor19998442010-08-13 15:35:05 +00002052unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2053 return CXSaveTranslationUnit_None;
2054}
2055
2056int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2057 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002058 if (!TU)
2059 return 1;
2060
2061 return static_cast<ASTUnit *>(TU)->Save(FileName);
2062}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002063
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002064void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002065 if (CTUnit) {
2066 // If the translation unit has been marked as unsafe to free, just discard
2067 // it.
2068 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2069 return;
2070
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002071 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002072 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002073}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002074
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002075unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2076 return CXReparse_None;
2077}
2078
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002079struct ReparseTranslationUnitInfo {
2080 CXTranslationUnit TU;
2081 unsigned num_unsaved_files;
2082 struct CXUnsavedFile *unsaved_files;
2083 unsigned options;
2084 int result;
2085};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002086static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002087 ReparseTranslationUnitInfo *RTUI =
2088 static_cast<ReparseTranslationUnitInfo*>(UserData);
2089 CXTranslationUnit TU = RTUI->TU;
2090 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2091 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2092 unsigned options = RTUI->options;
2093 (void) options;
2094 RTUI->result = 1;
2095
Douglas Gregorabc563f2010-07-19 21:46:24 +00002096 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002097 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002098
2099 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2100 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2101 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2102 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002103 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002104 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2105 Buffer));
2106 }
2107
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002108 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
2109 RemappedFiles.size()))
2110 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002111}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002112int clang_reparseTranslationUnit(CXTranslationUnit TU,
2113 unsigned num_unsaved_files,
2114 struct CXUnsavedFile *unsaved_files,
2115 unsigned options) {
2116 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2117 options, 0 };
2118 llvm::CrashRecoveryContext CRC;
2119
2120 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002121 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002122 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2123 return 1;
2124 }
2125
2126 return RTUI.result;
2127}
2128
Douglas Gregordf95a132010-08-09 20:45:32 +00002129
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002130CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002131 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002132 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002133
Steve Naroff77accc12009-09-03 18:19:54 +00002134 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002135 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002136}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002137
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002138CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002139 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002140 return Result;
2141}
2142
Ted Kremenekfb480492010-01-13 21:46:36 +00002143} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002144
Ted Kremenekfb480492010-01-13 21:46:36 +00002145//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002146// CXSourceLocation and CXSourceRange Operations.
2147//===----------------------------------------------------------------------===//
2148
Douglas Gregorb9790342010-01-22 21:44:22 +00002149extern "C" {
2150CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002151 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002152 return Result;
2153}
2154
2155unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002156 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2157 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2158 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002159}
2160
2161CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2162 CXFile file,
2163 unsigned line,
2164 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002165 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002166 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002167
Douglas Gregorb9790342010-01-22 21:44:22 +00002168 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2169 SourceLocation SLoc
2170 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002171 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002172 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002173
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002174 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002175}
2176
Douglas Gregor5352ac02010-01-28 00:27:43 +00002177CXSourceRange clang_getNullRange() {
2178 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2179 return Result;
2180}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002181
Douglas Gregor5352ac02010-01-28 00:27:43 +00002182CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2183 if (begin.ptr_data[0] != end.ptr_data[0] ||
2184 begin.ptr_data[1] != end.ptr_data[1])
2185 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002186
2187 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002188 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002189 return Result;
2190}
2191
Douglas Gregor46766dc2010-01-26 19:19:08 +00002192void clang_getInstantiationLocation(CXSourceLocation location,
2193 CXFile *file,
2194 unsigned *line,
2195 unsigned *column,
2196 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002197 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2198
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002199 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002200 if (file)
2201 *file = 0;
2202 if (line)
2203 *line = 0;
2204 if (column)
2205 *column = 0;
2206 if (offset)
2207 *offset = 0;
2208 return;
2209 }
2210
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002211 const SourceManager &SM =
2212 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002213 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002214
2215 if (file)
2216 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2217 if (line)
2218 *line = SM.getInstantiationLineNumber(InstLoc);
2219 if (column)
2220 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002221 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002222 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002223}
2224
Douglas Gregor1db19de2010-01-19 21:36:55 +00002225CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002226 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002227 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002228 return Result;
2229}
2230
2231CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002232 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002233 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002234 return Result;
2235}
2236
Douglas Gregorb9790342010-01-22 21:44:22 +00002237} // end: extern "C"
2238
Douglas Gregor1db19de2010-01-19 21:36:55 +00002239//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002240// CXFile Operations.
2241//===----------------------------------------------------------------------===//
2242
2243extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002244CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002245 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002246 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002247
Steve Naroff88145032009-10-27 14:35:18 +00002248 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002249 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002250}
2251
2252time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002253 if (!SFile)
2254 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002255
Steve Naroff88145032009-10-27 14:35:18 +00002256 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2257 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002258}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002259
Douglas Gregorb9790342010-01-22 21:44:22 +00002260CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2261 if (!tu)
2262 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002263
Douglas Gregorb9790342010-01-22 21:44:22 +00002264 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002265
Douglas Gregorb9790342010-01-22 21:44:22 +00002266 FileManager &FMgr = CXXUnit->getFileManager();
2267 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2268 return const_cast<FileEntry *>(File);
2269}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002270
Ted Kremenekfb480492010-01-13 21:46:36 +00002271} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002272
Ted Kremenekfb480492010-01-13 21:46:36 +00002273//===----------------------------------------------------------------------===//
2274// CXCursor Operations.
2275//===----------------------------------------------------------------------===//
2276
Ted Kremenekfb480492010-01-13 21:46:36 +00002277static Decl *getDeclFromExpr(Stmt *E) {
2278 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2279 return RefExpr->getDecl();
2280 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2281 return ME->getMemberDecl();
2282 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2283 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002284
Ted Kremenekfb480492010-01-13 21:46:36 +00002285 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2286 return getDeclFromExpr(CE->getCallee());
2287 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2288 return getDeclFromExpr(CE->getSubExpr());
2289 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2290 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002291
Ted Kremenekfb480492010-01-13 21:46:36 +00002292 return 0;
2293}
2294
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002295static SourceLocation getLocationFromExpr(Expr *E) {
2296 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2297 return /*FIXME:*/Msg->getLeftLoc();
2298 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2299 return DRE->getLocation();
2300 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2301 return Member->getMemberLoc();
2302 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2303 return Ivar->getLocation();
2304 return E->getLocStart();
2305}
2306
Ted Kremenekfb480492010-01-13 21:46:36 +00002307extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002308
2309unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002310 CXCursorVisitor visitor,
2311 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002312 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002313
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002314 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2315 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002316 return CursorVis.VisitChildren(parent);
2317}
2318
Douglas Gregor78205d42010-01-20 21:45:58 +00002319static CXString getDeclSpelling(Decl *D) {
2320 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2321 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002322 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002323
Douglas Gregor78205d42010-01-20 21:45:58 +00002324 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002325 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002326
Douglas Gregor78205d42010-01-20 21:45:58 +00002327 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2328 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2329 // and returns different names. NamedDecl returns the class name and
2330 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002331 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002332
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002333 if (isa<UsingDirectiveDecl>(D))
2334 return createCXString("");
2335
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002336 llvm::SmallString<1024> S;
2337 llvm::raw_svector_ostream os(S);
2338 ND->printName(os);
2339
2340 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002341}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002342
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002343CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002344 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002345 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002346
Steve Narofff334b4e2009-09-02 18:26:48 +00002347 if (clang_isReference(C.kind)) {
2348 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002349 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002350 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002351 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002352 }
2353 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002354 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002355 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002356 }
2357 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002358 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002359 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002360 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002361 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002362 case CXCursor_CXXBaseSpecifier: {
2363 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2364 return createCXString(B->getType().getAsString());
2365 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002366 case CXCursor_TypeRef: {
2367 TypeDecl *Type = getCursorTypeRef(C).first;
2368 assert(Type && "Missing type decl");
2369
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002370 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2371 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002372 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002373 case CXCursor_TemplateRef: {
2374 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002375 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002376
2377 return createCXString(Template->getNameAsString());
2378 }
Douglas Gregor69319002010-08-31 23:48:11 +00002379
2380 case CXCursor_NamespaceRef: {
2381 NamedDecl *NS = getCursorNamespaceRef(C).first;
2382 assert(NS && "Missing namespace decl");
2383
2384 return createCXString(NS->getNameAsString());
2385 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002386
Daniel Dunbaracca7252009-11-30 20:42:49 +00002387 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002388 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002389 }
2390 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002391
2392 if (clang_isExpression(C.kind)) {
2393 Decl *D = getDeclFromExpr(getCursorExpr(C));
2394 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002395 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002396 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002397 }
2398
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002399 if (C.kind == CXCursor_MacroInstantiation)
2400 return createCXString(getCursorMacroInstantiation(C)->getName()
2401 ->getNameStart());
2402
Douglas Gregor572feb22010-03-18 18:04:21 +00002403 if (C.kind == CXCursor_MacroDefinition)
2404 return createCXString(getCursorMacroDefinition(C)->getName()
2405 ->getNameStart());
2406
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002407 if (clang_isDeclaration(C.kind))
2408 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002409
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002410 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002411}
2412
Ted Kremeneke68fff62010-02-17 00:41:32 +00002413CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002414 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002415 case CXCursor_FunctionDecl:
2416 return createCXString("FunctionDecl");
2417 case CXCursor_TypedefDecl:
2418 return createCXString("TypedefDecl");
2419 case CXCursor_EnumDecl:
2420 return createCXString("EnumDecl");
2421 case CXCursor_EnumConstantDecl:
2422 return createCXString("EnumConstantDecl");
2423 case CXCursor_StructDecl:
2424 return createCXString("StructDecl");
2425 case CXCursor_UnionDecl:
2426 return createCXString("UnionDecl");
2427 case CXCursor_ClassDecl:
2428 return createCXString("ClassDecl");
2429 case CXCursor_FieldDecl:
2430 return createCXString("FieldDecl");
2431 case CXCursor_VarDecl:
2432 return createCXString("VarDecl");
2433 case CXCursor_ParmDecl:
2434 return createCXString("ParmDecl");
2435 case CXCursor_ObjCInterfaceDecl:
2436 return createCXString("ObjCInterfaceDecl");
2437 case CXCursor_ObjCCategoryDecl:
2438 return createCXString("ObjCCategoryDecl");
2439 case CXCursor_ObjCProtocolDecl:
2440 return createCXString("ObjCProtocolDecl");
2441 case CXCursor_ObjCPropertyDecl:
2442 return createCXString("ObjCPropertyDecl");
2443 case CXCursor_ObjCIvarDecl:
2444 return createCXString("ObjCIvarDecl");
2445 case CXCursor_ObjCInstanceMethodDecl:
2446 return createCXString("ObjCInstanceMethodDecl");
2447 case CXCursor_ObjCClassMethodDecl:
2448 return createCXString("ObjCClassMethodDecl");
2449 case CXCursor_ObjCImplementationDecl:
2450 return createCXString("ObjCImplementationDecl");
2451 case CXCursor_ObjCCategoryImplDecl:
2452 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002453 case CXCursor_CXXMethod:
2454 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002455 case CXCursor_UnexposedDecl:
2456 return createCXString("UnexposedDecl");
2457 case CXCursor_ObjCSuperClassRef:
2458 return createCXString("ObjCSuperClassRef");
2459 case CXCursor_ObjCProtocolRef:
2460 return createCXString("ObjCProtocolRef");
2461 case CXCursor_ObjCClassRef:
2462 return createCXString("ObjCClassRef");
2463 case CXCursor_TypeRef:
2464 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002465 case CXCursor_TemplateRef:
2466 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002467 case CXCursor_NamespaceRef:
2468 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002469 case CXCursor_UnexposedExpr:
2470 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002471 case CXCursor_BlockExpr:
2472 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002473 case CXCursor_DeclRefExpr:
2474 return createCXString("DeclRefExpr");
2475 case CXCursor_MemberRefExpr:
2476 return createCXString("MemberRefExpr");
2477 case CXCursor_CallExpr:
2478 return createCXString("CallExpr");
2479 case CXCursor_ObjCMessageExpr:
2480 return createCXString("ObjCMessageExpr");
2481 case CXCursor_UnexposedStmt:
2482 return createCXString("UnexposedStmt");
2483 case CXCursor_InvalidFile:
2484 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002485 case CXCursor_InvalidCode:
2486 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002487 case CXCursor_NoDeclFound:
2488 return createCXString("NoDeclFound");
2489 case CXCursor_NotImplemented:
2490 return createCXString("NotImplemented");
2491 case CXCursor_TranslationUnit:
2492 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002493 case CXCursor_UnexposedAttr:
2494 return createCXString("UnexposedAttr");
2495 case CXCursor_IBActionAttr:
2496 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002497 case CXCursor_IBOutletAttr:
2498 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002499 case CXCursor_IBOutletCollectionAttr:
2500 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002501 case CXCursor_PreprocessingDirective:
2502 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002503 case CXCursor_MacroDefinition:
2504 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002505 case CXCursor_MacroInstantiation:
2506 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002507 case CXCursor_Namespace:
2508 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002509 case CXCursor_LinkageSpec:
2510 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002511 case CXCursor_CXXBaseSpecifier:
2512 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002513 case CXCursor_Constructor:
2514 return createCXString("CXXConstructor");
2515 case CXCursor_Destructor:
2516 return createCXString("CXXDestructor");
2517 case CXCursor_ConversionFunction:
2518 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002519 case CXCursor_TemplateTypeParameter:
2520 return createCXString("TemplateTypeParameter");
2521 case CXCursor_NonTypeTemplateParameter:
2522 return createCXString("NonTypeTemplateParameter");
2523 case CXCursor_TemplateTemplateParameter:
2524 return createCXString("TemplateTemplateParameter");
2525 case CXCursor_FunctionTemplate:
2526 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002527 case CXCursor_ClassTemplate:
2528 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002529 case CXCursor_ClassTemplatePartialSpecialization:
2530 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002531 case CXCursor_NamespaceAlias:
2532 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002533 case CXCursor_UsingDirective:
2534 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002535 case CXCursor_UsingDeclaration:
2536 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002537 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002538
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002539 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002540 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002541}
Steve Naroff89922f82009-08-31 00:59:03 +00002542
Ted Kremeneke68fff62010-02-17 00:41:32 +00002543enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2544 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002545 CXClientData client_data) {
2546 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2547 *BestCursor = cursor;
2548 return CXChildVisit_Recurse;
2549}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002550
Douglas Gregorb9790342010-01-22 21:44:22 +00002551CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2552 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002553 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002554
Douglas Gregorb9790342010-01-22 21:44:22 +00002555 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002556 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2557
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002558 // Translate the given source location to make it point at the beginning of
2559 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002560 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002561
2562 // Guard against an invalid SourceLocation, or we may assert in one
2563 // of the following calls.
2564 if (SLoc.isInvalid())
2565 return clang_getNullCursor();
2566
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002567 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2568 CXXUnit->getASTContext().getLangOptions());
2569
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002570 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2571 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002572 // FIXME: Would be great to have a "hint" cursor, then walk from that
2573 // hint cursor upward until we find a cursor whose source range encloses
2574 // the region of interest, rather than starting from the translation unit.
2575 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002576 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002577 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002578 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002579 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002580 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002581}
2582
Ted Kremenek73885552009-11-17 19:28:59 +00002583CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002584 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002585}
2586
2587unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002588 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002589}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002590
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002591unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002592 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2593}
2594
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002595unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002596 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2597}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002598
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002599unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002600 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2601}
2602
Douglas Gregor97b98722010-01-19 23:20:36 +00002603unsigned clang_isExpression(enum CXCursorKind K) {
2604 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2605}
2606
2607unsigned clang_isStatement(enum CXCursorKind K) {
2608 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2609}
2610
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002611unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2612 return K == CXCursor_TranslationUnit;
2613}
2614
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002615unsigned clang_isPreprocessing(enum CXCursorKind K) {
2616 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2617}
2618
Ted Kremenekad6eff62010-03-08 21:17:29 +00002619unsigned clang_isUnexposed(enum CXCursorKind K) {
2620 switch (K) {
2621 case CXCursor_UnexposedDecl:
2622 case CXCursor_UnexposedExpr:
2623 case CXCursor_UnexposedStmt:
2624 case CXCursor_UnexposedAttr:
2625 return true;
2626 default:
2627 return false;
2628 }
2629}
2630
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002631CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002632 return C.kind;
2633}
2634
Douglas Gregor98258af2010-01-18 22:46:11 +00002635CXSourceLocation clang_getCursorLocation(CXCursor C) {
2636 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002637 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002638 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002639 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2640 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002641 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002642 }
2643
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002644 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002645 std::pair<ObjCProtocolDecl *, SourceLocation> P
2646 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002647 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002648 }
2649
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002650 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002651 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2652 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002653 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002654 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002655
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002656 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002657 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002658 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002659 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002660
2661 case CXCursor_TemplateRef: {
2662 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2663 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2664 }
2665
Douglas Gregor69319002010-08-31 23:48:11 +00002666 case CXCursor_NamespaceRef: {
2667 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2668 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2669 }
2670
Ted Kremenek3064ef92010-08-27 21:34:58 +00002671 case CXCursor_CXXBaseSpecifier: {
2672 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2673 return clang_getNullLocation();
2674 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002675
Douglas Gregorf46034a2010-01-18 23:41:10 +00002676 default:
2677 // FIXME: Need a way to enumerate all non-reference cases.
2678 llvm_unreachable("Missed a reference kind");
2679 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002680 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002681
2682 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002683 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002684 getLocationFromExpr(getCursorExpr(C)));
2685
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002686 if (C.kind == CXCursor_PreprocessingDirective) {
2687 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2688 return cxloc::translateSourceLocation(getCursorContext(C), L);
2689 }
Douglas Gregor48072312010-03-18 15:23:44 +00002690
2691 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002692 SourceLocation L
2693 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002694 return cxloc::translateSourceLocation(getCursorContext(C), L);
2695 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002696
2697 if (C.kind == CXCursor_MacroDefinition) {
2698 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2699 return cxloc::translateSourceLocation(getCursorContext(C), L);
2700 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002701
Ted Kremenek9a700d22010-05-12 06:16:13 +00002702 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002703 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002704
Douglas Gregorf46034a2010-01-18 23:41:10 +00002705 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002706 SourceLocation Loc = D->getLocation();
2707 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2708 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002709 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002710}
Douglas Gregora7bde202010-01-19 00:34:46 +00002711
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002712} // end extern "C"
2713
2714static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002715 if (clang_isReference(C.kind)) {
2716 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002717 case CXCursor_ObjCSuperClassRef:
2718 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002719
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002720 case CXCursor_ObjCProtocolRef:
2721 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002722
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002723 case CXCursor_ObjCClassRef:
2724 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002725
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002726 case CXCursor_TypeRef:
2727 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002728
2729 case CXCursor_TemplateRef:
2730 return getCursorTemplateRef(C).second;
2731
Douglas Gregor69319002010-08-31 23:48:11 +00002732 case CXCursor_NamespaceRef:
2733 return getCursorNamespaceRef(C).second;
2734
Ted Kremenek3064ef92010-08-27 21:34:58 +00002735 case CXCursor_CXXBaseSpecifier:
2736 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2737 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002738
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002739 default:
2740 // FIXME: Need a way to enumerate all non-reference cases.
2741 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002742 }
2743 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002744
2745 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002746 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002747
2748 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002749 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002750
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002751 if (C.kind == CXCursor_PreprocessingDirective)
2752 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002753
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002754 if (C.kind == CXCursor_MacroInstantiation)
2755 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002756
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002757 if (C.kind == CXCursor_MacroDefinition)
2758 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002759
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002760 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2761 return getCursorDecl(C)->getSourceRange();
2762
2763 return SourceRange();
2764}
2765
2766extern "C" {
2767
2768CXSourceRange clang_getCursorExtent(CXCursor C) {
2769 SourceRange R = getRawCursorExtent(C);
2770 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002771 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002772
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002773 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002774}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002775
2776CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002777 if (clang_isInvalid(C.kind))
2778 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002779
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002780 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002781 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002782 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002783
Douglas Gregor97b98722010-01-19 23:20:36 +00002784 if (clang_isExpression(C.kind)) {
2785 Decl *D = getDeclFromExpr(getCursorExpr(C));
2786 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002787 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002788 return clang_getNullCursor();
2789 }
2790
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002791 if (C.kind == CXCursor_MacroInstantiation) {
2792 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2793 return MakeMacroDefinitionCursor(Def, CXXUnit);
2794 }
2795
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002796 if (!clang_isReference(C.kind))
2797 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002798
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002799 switch (C.kind) {
2800 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002801 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002802
2803 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002804 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002805
2806 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002807 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002808
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002809 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002810 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002811
2812 case CXCursor_TemplateRef:
2813 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2814
Douglas Gregor69319002010-08-31 23:48:11 +00002815 case CXCursor_NamespaceRef:
2816 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2817
Ted Kremenek3064ef92010-08-27 21:34:58 +00002818 case CXCursor_CXXBaseSpecifier: {
2819 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2820 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2821 CXXUnit));
2822 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002823
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002824 default:
2825 // We would prefer to enumerate all non-reference cursor kinds here.
2826 llvm_unreachable("Unhandled reference cursor kind");
2827 break;
2828 }
2829 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002830
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002831 return clang_getNullCursor();
2832}
2833
Douglas Gregorb6998662010-01-19 19:34:47 +00002834CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002835 if (clang_isInvalid(C.kind))
2836 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002837
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002838 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002839
Douglas Gregorb6998662010-01-19 19:34:47 +00002840 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002841 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002842 C = clang_getCursorReferenced(C);
2843 WasReference = true;
2844 }
2845
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002846 if (C.kind == CXCursor_MacroInstantiation)
2847 return clang_getCursorReferenced(C);
2848
Douglas Gregorb6998662010-01-19 19:34:47 +00002849 if (!clang_isDeclaration(C.kind))
2850 return clang_getNullCursor();
2851
2852 Decl *D = getCursorDecl(C);
2853 if (!D)
2854 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002855
Douglas Gregorb6998662010-01-19 19:34:47 +00002856 switch (D->getKind()) {
2857 // Declaration kinds that don't really separate the notions of
2858 // declaration and definition.
2859 case Decl::Namespace:
2860 case Decl::Typedef:
2861 case Decl::TemplateTypeParm:
2862 case Decl::EnumConstant:
2863 case Decl::Field:
2864 case Decl::ObjCIvar:
2865 case Decl::ObjCAtDefsField:
2866 case Decl::ImplicitParam:
2867 case Decl::ParmVar:
2868 case Decl::NonTypeTemplateParm:
2869 case Decl::TemplateTemplateParm:
2870 case Decl::ObjCCategoryImpl:
2871 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002872 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002873 case Decl::LinkageSpec:
2874 case Decl::ObjCPropertyImpl:
2875 case Decl::FileScopeAsm:
2876 case Decl::StaticAssert:
2877 case Decl::Block:
2878 return C;
2879
2880 // Declaration kinds that don't make any sense here, but are
2881 // nonetheless harmless.
2882 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002883 break;
2884
2885 // Declaration kinds for which the definition is not resolvable.
2886 case Decl::UnresolvedUsingTypename:
2887 case Decl::UnresolvedUsingValue:
2888 break;
2889
2890 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002891 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2892 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002893
2894 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002895 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002896
2897 case Decl::Enum:
2898 case Decl::Record:
2899 case Decl::CXXRecord:
2900 case Decl::ClassTemplateSpecialization:
2901 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002902 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002903 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002904 return clang_getNullCursor();
2905
2906 case Decl::Function:
2907 case Decl::CXXMethod:
2908 case Decl::CXXConstructor:
2909 case Decl::CXXDestructor:
2910 case Decl::CXXConversion: {
2911 const FunctionDecl *Def = 0;
2912 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002913 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002914 return clang_getNullCursor();
2915 }
2916
2917 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002918 // Ask the variable if it has a definition.
2919 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2920 return MakeCXCursor(Def, CXXUnit);
2921 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002922 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002923
Douglas Gregorb6998662010-01-19 19:34:47 +00002924 case Decl::FunctionTemplate: {
2925 const FunctionDecl *Def = 0;
2926 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002927 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002928 return clang_getNullCursor();
2929 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002930
Douglas Gregorb6998662010-01-19 19:34:47 +00002931 case Decl::ClassTemplate: {
2932 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002933 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002934 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002935 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002936 return clang_getNullCursor();
2937 }
2938
2939 case Decl::Using: {
2940 UsingDecl *Using = cast<UsingDecl>(D);
2941 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002942 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2943 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002944 S != SEnd; ++S) {
2945 if (Def != clang_getNullCursor()) {
2946 // FIXME: We have no way to return multiple results.
2947 return clang_getNullCursor();
2948 }
2949
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002950 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002951 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002952 }
2953
2954 return Def;
2955 }
2956
2957 case Decl::UsingShadow:
2958 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002959 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002960 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002961
2962 case Decl::ObjCMethod: {
2963 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2964 if (Method->isThisDeclarationADefinition())
2965 return C;
2966
2967 // Dig out the method definition in the associated
2968 // @implementation, if we have it.
2969 // FIXME: The ASTs should make finding the definition easier.
2970 if (ObjCInterfaceDecl *Class
2971 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2972 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2973 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2974 Method->isInstanceMethod()))
2975 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002976 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002977
2978 return clang_getNullCursor();
2979 }
2980
2981 case Decl::ObjCCategory:
2982 if (ObjCCategoryImplDecl *Impl
2983 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002984 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002985 return clang_getNullCursor();
2986
2987 case Decl::ObjCProtocol:
2988 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2989 return C;
2990 return clang_getNullCursor();
2991
2992 case Decl::ObjCInterface:
2993 // There are two notions of a "definition" for an Objective-C
2994 // class: the interface and its implementation. When we resolved a
2995 // reference to an Objective-C class, produce the @interface as
2996 // the definition; when we were provided with the interface,
2997 // produce the @implementation as the definition.
2998 if (WasReference) {
2999 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3000 return C;
3001 } else if (ObjCImplementationDecl *Impl
3002 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003003 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003004 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003005
Douglas Gregorb6998662010-01-19 19:34:47 +00003006 case Decl::ObjCProperty:
3007 // FIXME: We don't really know where to find the
3008 // ObjCPropertyImplDecls that implement this property.
3009 return clang_getNullCursor();
3010
3011 case Decl::ObjCCompatibleAlias:
3012 if (ObjCInterfaceDecl *Class
3013 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3014 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003015 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003016
Douglas Gregorb6998662010-01-19 19:34:47 +00003017 return clang_getNullCursor();
3018
3019 case Decl::ObjCForwardProtocol: {
3020 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
3021 if (Forward->protocol_size() == 1)
3022 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003023 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003024 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003025
3026 // FIXME: Cannot return multiple definitions.
3027 return clang_getNullCursor();
3028 }
3029
3030 case Decl::ObjCClass: {
3031 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
3032 if (Class->size() == 1) {
3033 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
3034 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003035 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003036 return clang_getNullCursor();
3037 }
3038
3039 // FIXME: Cannot return multiple definitions.
3040 return clang_getNullCursor();
3041 }
3042
3043 case Decl::Friend:
3044 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003045 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003046 return clang_getNullCursor();
3047
3048 case Decl::FriendTemplate:
3049 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003050 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003051 return clang_getNullCursor();
3052 }
3053
3054 return clang_getNullCursor();
3055}
3056
3057unsigned clang_isCursorDefinition(CXCursor C) {
3058 if (!clang_isDeclaration(C.kind))
3059 return 0;
3060
3061 return clang_getCursorDefinition(C) == C;
3062}
3063
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003064void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003065 const char **startBuf,
3066 const char **endBuf,
3067 unsigned *startLine,
3068 unsigned *startColumn,
3069 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003070 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003071 assert(getCursorDecl(C) && "CXCursor has null decl");
3072 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003073 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3074 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003075
Steve Naroff4ade6d62009-09-23 17:52:52 +00003076 SourceManager &SM = FD->getASTContext().getSourceManager();
3077 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3078 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3079 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3080 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3081 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3082 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3083}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003084
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003085void clang_enableStackTraces(void) {
3086 llvm::sys::PrintStackTraceOnErrorSignal();
3087}
3088
Ted Kremenekfb480492010-01-13 21:46:36 +00003089} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003090
Ted Kremenekfb480492010-01-13 21:46:36 +00003091//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003092// Token-based Operations.
3093//===----------------------------------------------------------------------===//
3094
3095/* CXToken layout:
3096 * int_data[0]: a CXTokenKind
3097 * int_data[1]: starting token location
3098 * int_data[2]: token length
3099 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003100 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003101 * otherwise unused.
3102 */
3103extern "C" {
3104
3105CXTokenKind clang_getTokenKind(CXToken CXTok) {
3106 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3107}
3108
3109CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3110 switch (clang_getTokenKind(CXTok)) {
3111 case CXToken_Identifier:
3112 case CXToken_Keyword:
3113 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003114 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3115 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003116
3117 case CXToken_Literal: {
3118 // We have stashed the starting pointer in the ptr_data field. Use it.
3119 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003120 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003121 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003122
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003123 case CXToken_Punctuation:
3124 case CXToken_Comment:
3125 break;
3126 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003127
3128 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003129 // deconstructing the source location.
3130 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3131 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003132 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003133
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003134 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3135 std::pair<FileID, unsigned> LocInfo
3136 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003137 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003138 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003139 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3140 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003141 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003142
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003143 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003144}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003145
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003146CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3147 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3148 if (!CXXUnit)
3149 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003150
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003151 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3152 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3153}
3154
3155CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3156 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003157 if (!CXXUnit)
3158 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003159
3160 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003161 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3162}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003163
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003164void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3165 CXToken **Tokens, unsigned *NumTokens) {
3166 if (Tokens)
3167 *Tokens = 0;
3168 if (NumTokens)
3169 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003170
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003171 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3172 if (!CXXUnit || !Tokens || !NumTokens)
3173 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003174
Douglas Gregorbdf60622010-03-05 21:16:25 +00003175 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3176
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003177 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003178 if (R.isInvalid())
3179 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003180
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003181 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3182 std::pair<FileID, unsigned> BeginLocInfo
3183 = SourceMgr.getDecomposedLoc(R.getBegin());
3184 std::pair<FileID, unsigned> EndLocInfo
3185 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003186
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003187 // Cannot tokenize across files.
3188 if (BeginLocInfo.first != EndLocInfo.first)
3189 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003190
3191 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003192 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003193 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003194 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003195 if (Invalid)
3196 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003197
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003198 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3199 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003200 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003201 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003202
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003203 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003204 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003205 llvm::SmallVector<CXToken, 32> CXTokens;
3206 Token Tok;
3207 do {
3208 // Lex the next token
3209 Lex.LexFromRawLexer(Tok);
3210 if (Tok.is(tok::eof))
3211 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003212
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003213 // Initialize the CXToken.
3214 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003215
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003216 // - Common fields
3217 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3218 CXTok.int_data[2] = Tok.getLength();
3219 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003220
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003221 // - Kind-specific fields
3222 if (Tok.isLiteral()) {
3223 CXTok.int_data[0] = CXToken_Literal;
3224 CXTok.ptr_data = (void *)Tok.getLiteralData();
3225 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003226 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003227 std::pair<FileID, unsigned> LocInfo
3228 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003229 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003230 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003231 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3232 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003233 return;
3234
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003235 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003236 IdentifierInfo *II
3237 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003238
3239 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3240 CXTok.int_data[0] = CXToken_Keyword;
3241 }
3242 else {
3243 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3244 CXToken_Identifier
3245 : CXToken_Keyword;
3246 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003247 CXTok.ptr_data = II;
3248 } else if (Tok.is(tok::comment)) {
3249 CXTok.int_data[0] = CXToken_Comment;
3250 CXTok.ptr_data = 0;
3251 } else {
3252 CXTok.int_data[0] = CXToken_Punctuation;
3253 CXTok.ptr_data = 0;
3254 }
3255 CXTokens.push_back(CXTok);
3256 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003257
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003258 if (CXTokens.empty())
3259 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003260
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003261 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3262 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3263 *NumTokens = CXTokens.size();
3264}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003265
Ted Kremenek6db61092010-05-05 00:55:15 +00003266void clang_disposeTokens(CXTranslationUnit TU,
3267 CXToken *Tokens, unsigned NumTokens) {
3268 free(Tokens);
3269}
3270
3271} // end: extern "C"
3272
3273//===----------------------------------------------------------------------===//
3274// Token annotation APIs.
3275//===----------------------------------------------------------------------===//
3276
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003277typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003278static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3279 CXCursor parent,
3280 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003281namespace {
3282class AnnotateTokensWorker {
3283 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003284 CXToken *Tokens;
3285 CXCursor *Cursors;
3286 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003287 unsigned TokIdx;
3288 CursorVisitor AnnotateVis;
3289 SourceManager &SrcMgr;
3290
3291 bool MoreTokens() const { return TokIdx < NumTokens; }
3292 unsigned NextToken() const { return TokIdx; }
3293 void AdvanceToken() { ++TokIdx; }
3294 SourceLocation GetTokenLoc(unsigned tokI) {
3295 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3296 }
3297
Ted Kremenek6db61092010-05-05 00:55:15 +00003298public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003299 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003300 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3301 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003302 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003303 NumTokens(numTokens), TokIdx(0),
3304 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3305 Decl::MaxPCHLevel, RegionOfInterest),
3306 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003307
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003308 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003309 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003310 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003311};
3312}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003313
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003314void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3315 // Walk the AST within the region of interest, annotating tokens
3316 // along the way.
3317 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003318
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003319 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3320 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3321 if (Pos != Annotated.end())
3322 Cursors[I] = Pos->second;
3323 }
3324
3325 // Finish up annotating any tokens left.
3326 if (!MoreTokens())
3327 return;
3328
3329 const CXCursor &C = clang_getNullCursor();
3330 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3331 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3332 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003333 }
3334}
3335
Ted Kremenek6db61092010-05-05 00:55:15 +00003336enum CXChildVisitResult
3337AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003338 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3339 // We can always annotate a preprocessing directive/macro instantiation.
3340 if (clang_isPreprocessing(cursor.kind)) {
3341 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003342 return CXChildVisit_Recurse;
3343 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003344
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003345 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003346
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003347 if (cursorRange.isInvalid())
3348 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003349
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003350 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3351
Ted Kremeneka333c662010-05-12 05:29:33 +00003352 // Adjust the annotated range based specific declarations.
3353 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3354 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003355 Decl *D = cxcursor::getCursorDecl(cursor);
3356 // Don't visit synthesized ObjC methods, since they have no syntatic
3357 // representation in the source.
3358 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3359 if (MD->isSynthesized())
3360 return CXChildVisit_Continue;
3361 }
3362 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003363 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3364 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003365 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003366 if (TLoc.isValid() &&
3367 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003368 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003369 }
3370 }
3371 }
3372
Ted Kremenek3f404602010-08-14 01:14:06 +00003373 // If the location of the cursor occurs within a macro instantiation, record
3374 // the spelling location of the cursor in our annotation map. We can then
3375 // paper over the token labelings during a post-processing step to try and
3376 // get cursor mappings for tokens that are the *arguments* of a macro
3377 // instantiation.
3378 if (L.isMacroID()) {
3379 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3380 // Only invalidate the old annotation if it isn't part of a preprocessing
3381 // directive. Here we assume that the default construction of CXCursor
3382 // results in CXCursor.kind being an initialized value (i.e., 0). If
3383 // this isn't the case, we can fix by doing lookup + insertion.
3384
3385 CXCursor &oldC = Annotated[rawEncoding];
3386 if (!clang_isPreprocessing(oldC.kind))
3387 oldC = cursor;
3388 }
3389
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003390 const enum CXCursorKind K = clang_getCursorKind(parent);
3391 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003392 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3393 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003394
3395 while (MoreTokens()) {
3396 const unsigned I = NextToken();
3397 SourceLocation TokLoc = GetTokenLoc(I);
3398 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3399 case RangeBefore:
3400 Cursors[I] = updateC;
3401 AdvanceToken();
3402 continue;
3403 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003404 case RangeOverlap:
3405 break;
3406 }
3407 break;
3408 }
3409
3410 // Visit children to get their cursor information.
3411 const unsigned BeforeChildren = NextToken();
3412 VisitChildren(cursor);
3413 const unsigned AfterChildren = NextToken();
3414
3415 // Adjust 'Last' to the last token within the extent of the cursor.
3416 while (MoreTokens()) {
3417 const unsigned I = NextToken();
3418 SourceLocation TokLoc = GetTokenLoc(I);
3419 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3420 case RangeBefore:
3421 assert(0 && "Infeasible");
3422 case RangeAfter:
3423 break;
3424 case RangeOverlap:
3425 Cursors[I] = updateC;
3426 AdvanceToken();
3427 continue;
3428 }
3429 break;
3430 }
3431 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003432
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003433 // Scan the tokens that are at the beginning of the cursor, but are not
3434 // capture by the child cursors.
3435
3436 // For AST elements within macros, rely on a post-annotate pass to
3437 // to correctly annotate the tokens with cursors. Otherwise we can
3438 // get confusing results of having tokens that map to cursors that really
3439 // are expanded by an instantiation.
3440 if (L.isMacroID())
3441 cursor = clang_getNullCursor();
3442
3443 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3444 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3445 break;
3446 Cursors[I] = cursor;
3447 }
3448 // Scan the tokens that are at the end of the cursor, but are not captured
3449 // but the child cursors.
3450 for (unsigned I = AfterChildren; I != Last; ++I)
3451 Cursors[I] = cursor;
3452
3453 TokIdx = Last;
3454 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003455}
3456
Ted Kremenek6db61092010-05-05 00:55:15 +00003457static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3458 CXCursor parent,
3459 CXClientData client_data) {
3460 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3461}
3462
3463extern "C" {
3464
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003465void clang_annotateTokens(CXTranslationUnit TU,
3466 CXToken *Tokens, unsigned NumTokens,
3467 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003468
3469 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003470 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003471
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003472 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003473 if (!CXXUnit) {
3474 // Any token we don't specifically annotate will have a NULL cursor.
3475 const CXCursor &C = clang_getNullCursor();
3476 for (unsigned I = 0; I != NumTokens; ++I)
3477 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003478 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003479 }
3480
Douglas Gregorbdf60622010-03-05 21:16:25 +00003481 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003482
Douglas Gregor0396f462010-03-19 05:22:59 +00003483 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003484 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003485 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3486 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003487 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3488 clang_getTokenLocation(TU,
3489 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003490
Douglas Gregor0396f462010-03-19 05:22:59 +00003491 // A mapping from the source locations found when re-lexing or traversing the
3492 // region of interest to the corresponding cursors.
3493 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003494
3495 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003496 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003497 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3498 std::pair<FileID, unsigned> BeginLocInfo
3499 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3500 std::pair<FileID, unsigned> EndLocInfo
3501 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003502
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003503 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003504 bool Invalid = false;
3505 if (BeginLocInfo.first == EndLocInfo.first &&
3506 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3507 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003508 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3509 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003510 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003511 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003512 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003513
3514 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003515 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003516 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003517 Token Tok;
3518 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003519
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003520 reprocess:
3521 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3522 // We have found a preprocessing directive. Gobble it up so that we
3523 // don't see it while preprocessing these tokens later, but keep track of
3524 // all of the token locations inside this preprocessing directive so that
3525 // we can annotate them appropriately.
3526 //
3527 // FIXME: Some simple tests here could identify macro definitions and
3528 // #undefs, to provide specific cursor kinds for those.
3529 std::vector<SourceLocation> Locations;
3530 do {
3531 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003532 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003533 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003534
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003535 using namespace cxcursor;
3536 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003537 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3538 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003539 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003540 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3541 Annotated[Locations[I].getRawEncoding()] = Cursor;
3542 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003543
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003544 if (Tok.isAtStartOfLine())
3545 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003546
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003547 continue;
3548 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003549
Douglas Gregor48072312010-03-18 15:23:44 +00003550 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003551 break;
3552 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003553 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003554
Douglas Gregor0396f462010-03-19 05:22:59 +00003555 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003556 // a specific cursor.
3557 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3558 CXXUnit, RegionOfInterest);
3559 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003560}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003561} // end: extern "C"
3562
3563//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003564// Operations for querying linkage of a cursor.
3565//===----------------------------------------------------------------------===//
3566
3567extern "C" {
3568CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003569 if (!clang_isDeclaration(cursor.kind))
3570 return CXLinkage_Invalid;
3571
Ted Kremenek16b42592010-03-03 06:36:57 +00003572 Decl *D = cxcursor::getCursorDecl(cursor);
3573 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3574 switch (ND->getLinkage()) {
3575 case NoLinkage: return CXLinkage_NoLinkage;
3576 case InternalLinkage: return CXLinkage_Internal;
3577 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3578 case ExternalLinkage: return CXLinkage_External;
3579 };
3580
3581 return CXLinkage_Invalid;
3582}
3583} // end: extern "C"
3584
3585//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003586// Operations for querying language of a cursor.
3587//===----------------------------------------------------------------------===//
3588
3589static CXLanguageKind getDeclLanguage(const Decl *D) {
3590 switch (D->getKind()) {
3591 default:
3592 break;
3593 case Decl::ImplicitParam:
3594 case Decl::ObjCAtDefsField:
3595 case Decl::ObjCCategory:
3596 case Decl::ObjCCategoryImpl:
3597 case Decl::ObjCClass:
3598 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003599 case Decl::ObjCForwardProtocol:
3600 case Decl::ObjCImplementation:
3601 case Decl::ObjCInterface:
3602 case Decl::ObjCIvar:
3603 case Decl::ObjCMethod:
3604 case Decl::ObjCProperty:
3605 case Decl::ObjCPropertyImpl:
3606 case Decl::ObjCProtocol:
3607 return CXLanguage_ObjC;
3608 case Decl::CXXConstructor:
3609 case Decl::CXXConversion:
3610 case Decl::CXXDestructor:
3611 case Decl::CXXMethod:
3612 case Decl::CXXRecord:
3613 case Decl::ClassTemplate:
3614 case Decl::ClassTemplatePartialSpecialization:
3615 case Decl::ClassTemplateSpecialization:
3616 case Decl::Friend:
3617 case Decl::FriendTemplate:
3618 case Decl::FunctionTemplate:
3619 case Decl::LinkageSpec:
3620 case Decl::Namespace:
3621 case Decl::NamespaceAlias:
3622 case Decl::NonTypeTemplateParm:
3623 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003624 case Decl::TemplateTemplateParm:
3625 case Decl::TemplateTypeParm:
3626 case Decl::UnresolvedUsingTypename:
3627 case Decl::UnresolvedUsingValue:
3628 case Decl::Using:
3629 case Decl::UsingDirective:
3630 case Decl::UsingShadow:
3631 return CXLanguage_CPlusPlus;
3632 }
3633
3634 return CXLanguage_C;
3635}
3636
3637extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003638
3639enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3640 if (clang_isDeclaration(cursor.kind))
3641 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3642 if (D->hasAttr<UnavailableAttr>() ||
3643 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3644 return CXAvailability_Available;
3645
3646 if (D->hasAttr<DeprecatedAttr>())
3647 return CXAvailability_Deprecated;
3648 }
3649
3650 return CXAvailability_Available;
3651}
3652
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003653CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3654 if (clang_isDeclaration(cursor.kind))
3655 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3656
3657 return CXLanguage_Invalid;
3658}
3659} // end: extern "C"
3660
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003661
3662//===----------------------------------------------------------------------===//
3663// C++ AST instrospection.
3664//===----------------------------------------------------------------------===//
3665
3666extern "C" {
3667unsigned clang_CXXMethod_isStatic(CXCursor C) {
3668 if (!clang_isDeclaration(C.kind))
3669 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003670
3671 CXXMethodDecl *Method = 0;
3672 Decl *D = cxcursor::getCursorDecl(C);
3673 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3674 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3675 else
3676 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3677 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003678}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003679
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003680} // end: extern "C"
3681
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003682//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003683// Attribute introspection.
3684//===----------------------------------------------------------------------===//
3685
3686extern "C" {
3687CXType clang_getIBOutletCollectionType(CXCursor C) {
3688 if (C.kind != CXCursor_IBOutletCollectionAttr)
3689 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3690
3691 IBOutletCollectionAttr *A =
3692 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3693
3694 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3695}
3696} // end: extern "C"
3697
3698//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003699// CXString Operations.
3700//===----------------------------------------------------------------------===//
3701
3702extern "C" {
3703const char *clang_getCString(CXString string) {
3704 return string.Spelling;
3705}
3706
3707void clang_disposeString(CXString string) {
3708 if (string.MustFreeString && string.Spelling)
3709 free((void*)string.Spelling);
3710}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003711
Ted Kremenekfb480492010-01-13 21:46:36 +00003712} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003713
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003714namespace clang { namespace cxstring {
3715CXString createCXString(const char *String, bool DupString){
3716 CXString Str;
3717 if (DupString) {
3718 Str.Spelling = strdup(String);
3719 Str.MustFreeString = 1;
3720 } else {
3721 Str.Spelling = String;
3722 Str.MustFreeString = 0;
3723 }
3724 return Str;
3725}
3726
3727CXString createCXString(llvm::StringRef String, bool DupString) {
3728 CXString Result;
3729 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3730 char *Spelling = (char *)malloc(String.size() + 1);
3731 memmove(Spelling, String.data(), String.size());
3732 Spelling[String.size()] = 0;
3733 Result.Spelling = Spelling;
3734 Result.MustFreeString = 1;
3735 } else {
3736 Result.Spelling = String.data();
3737 Result.MustFreeString = 0;
3738 }
3739 return Result;
3740}
3741}}
3742
Ted Kremenek04bb7162010-01-22 22:44:15 +00003743//===----------------------------------------------------------------------===//
3744// Misc. utility functions.
3745//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003746
Ted Kremenek04bb7162010-01-22 22:44:15 +00003747extern "C" {
3748
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003749CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003750 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003751}
3752
3753} // end: extern "C"