blob: 19dd44b8cf28c695378a517f2e480830c52afe75 [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);
Douglas Gregor25d63622010-09-03 17:35:34 +0000396 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000397};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000398
Ted Kremenekab188932010-01-05 19:32:54 +0000399} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000400
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000401static SourceRange getRawCursorExtent(CXCursor C);
402
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000403RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000404 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
405}
406
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407/// \brief Visit the given cursor and, if requested by the visitor,
408/// its children.
409///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000410/// \param Cursor the cursor to visit.
411///
412/// \param CheckRegionOfInterest if true, then the caller already checked that
413/// this cursor is within the region of interest.
414///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000415/// \returns true if the visitation should be aborted, false if it
416/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000417bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418 if (clang_isInvalid(Cursor.kind))
419 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000420
Douglas Gregorb1373d02010-01-20 20:59:29 +0000421 if (clang_isDeclaration(Cursor.kind)) {
422 Decl *D = getCursorDecl(Cursor);
423 assert(D && "Invalid declaration cursor");
424 if (D->getPCHLevel() > MaxPCHLevel)
425 return false;
426
427 if (D->isImplicit())
428 return false;
429 }
430
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000431 // If we have a range of interest, and this cursor doesn't intersect with it,
432 // we're done.
433 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000434 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000435 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000436 return false;
437 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000438
Douglas Gregorb1373d02010-01-20 20:59:29 +0000439 switch (Visitor(Cursor, Parent, ClientData)) {
440 case CXChildVisit_Break:
441 return true;
442
443 case CXChildVisit_Continue:
444 return false;
445
446 case CXChildVisit_Recurse:
447 return VisitChildren(Cursor);
448 }
449
Douglas Gregorfd643772010-01-25 16:45:46 +0000450 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451}
452
Douglas Gregor788f5a12010-03-20 00:41:21 +0000453std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
454CursorVisitor::getPreprocessedEntities() {
455 PreprocessingRecord &PPRec
456 = *TU->getPreprocessor().getPreprocessingRecord();
457
458 bool OnlyLocalDecls
459 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
460
461 // There is no region of interest; we have to walk everything.
462 if (RegionOfInterest.isInvalid())
463 return std::make_pair(PPRec.begin(OnlyLocalDecls),
464 PPRec.end(OnlyLocalDecls));
465
466 // Find the file in which the region of interest lands.
467 SourceManager &SM = TU->getSourceManager();
468 std::pair<FileID, unsigned> Begin
469 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
470 std::pair<FileID, unsigned> End
471 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
472
473 // The region of interest spans files; we have to walk everything.
474 if (Begin.first != End.first)
475 return std::make_pair(PPRec.begin(OnlyLocalDecls),
476 PPRec.end(OnlyLocalDecls));
477
478 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
479 = TU->getPreprocessedEntitiesByFile();
480 if (ByFileMap.empty()) {
481 // Build the mapping from files to sets of preprocessed entities.
482 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
483 EEnd = PPRec.end(OnlyLocalDecls);
484 E != EEnd; ++E) {
485 std::pair<FileID, unsigned> P
486 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
487 ByFileMap[P.first].push_back(*E);
488 }
489 }
490
491 return std::make_pair(ByFileMap[Begin.first].begin(),
492 ByFileMap[Begin.first].end());
493}
494
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495/// \brief Visit the children of the given cursor.
496///
497/// \returns true if the visitation should be aborted, false if it
498/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000499bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000500 if (clang_isReference(Cursor.kind)) {
501 // By definition, references have no children.
502 return false;
503 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000504
505 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000506 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000507 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000508
Douglas Gregorb1373d02010-01-20 20:59:29 +0000509 if (clang_isDeclaration(Cursor.kind)) {
510 Decl *D = getCursorDecl(Cursor);
511 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000512 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000514
Douglas Gregora59e3902010-01-21 23:27:09 +0000515 if (clang_isStatement(Cursor.kind))
516 return Visit(getCursorStmt(Cursor));
517 if (clang_isExpression(Cursor.kind))
518 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000519
Douglas Gregorb1373d02010-01-20 20:59:29 +0000520 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000521 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000522 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
523 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000524 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
525 TLEnd = CXXUnit->top_level_end();
526 TL != TLEnd; ++TL) {
527 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000528 return true;
529 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000530 } else if (VisitDeclContext(
531 CXXUnit->getASTContext().getTranslationUnitDecl()))
532 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000533
Douglas Gregor0396f462010-03-19 05:22:59 +0000534 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000535 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000536 // FIXME: Once we have the ability to deserialize a preprocessing record,
537 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000538 PreprocessingRecord::iterator E, EEnd;
539 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000540 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
541 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
542 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000543
Douglas Gregor0396f462010-03-19 05:22:59 +0000544 continue;
545 }
546
547 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
548 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
549 return true;
550
551 continue;
552 }
553 }
554 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000555 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000556 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000557
Douglas Gregorb1373d02010-01-20 20:59:29 +0000558 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 return false;
560}
561
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000562bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000563 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
564 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000565
Ted Kremenek664cffd2010-07-22 11:30:19 +0000566 if (Stmt *Body = B->getBody())
567 return Visit(MakeCXCursor(Body, StmtParent, TU));
568
569 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000570}
571
Douglas Gregorb1373d02010-01-20 20:59:29 +0000572bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000573 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000574 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000575
Ted Kremenek23173d72010-05-18 21:09:07 +0000576 Decl *D = *I;
577 if (D->getLexicalDeclContext() != DC)
578 continue;
579
580 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000581
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000582 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000583 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000584 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000585 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000586
587 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000588 case RangeBefore:
589 // This declaration comes before the region of interest; skip it.
590 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000591
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000592 case RangeAfter:
593 // This declaration comes after the region of interest; we're done.
594 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000595
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000596 case RangeOverlap:
597 // This declaration overlaps the region of interest; visit it.
598 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000599 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000600 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000601
Daniel Dunbard52864b2010-02-14 10:02:57 +0000602 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000603 return true;
604 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000605
Douglas Gregorb1373d02010-01-20 20:59:29 +0000606 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000607}
608
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000609bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
610 llvm_unreachable("Translation units are visited directly by Visit()");
611 return false;
612}
613
614bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
615 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
616 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000617
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000618 return false;
619}
620
621bool CursorVisitor::VisitTagDecl(TagDecl *D) {
622 return VisitDeclContext(D);
623}
624
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000625bool CursorVisitor::VisitClassTemplateSpecializationDecl(
626 ClassTemplateSpecializationDecl *D) {
627 bool ShouldVisitBody = false;
628 switch (D->getSpecializationKind()) {
629 case TSK_Undeclared:
630 case TSK_ImplicitInstantiation:
631 // Nothing to visit
632 return false;
633
634 case TSK_ExplicitInstantiationDeclaration:
635 case TSK_ExplicitInstantiationDefinition:
636 break;
637
638 case TSK_ExplicitSpecialization:
639 ShouldVisitBody = true;
640 break;
641 }
642
643 // Visit the template arguments used in the specialization.
644 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
645 TypeLoc TL = SpecType->getTypeLoc();
646 if (TemplateSpecializationTypeLoc *TSTLoc
647 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
648 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
649 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
650 return true;
651 }
652 }
653
654 if (ShouldVisitBody && VisitCXXRecordDecl(D))
655 return true;
656
657 return false;
658}
659
Douglas Gregor74dbe642010-08-31 19:31:58 +0000660bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
661 ClassTemplatePartialSpecializationDecl *D) {
662 // FIXME: Visit the "outer" template parameter lists on the TagDecl
663 // before visiting these template parameters.
664 if (VisitTemplateParameters(D->getTemplateParameters()))
665 return true;
666
667 // Visit the partial specialization arguments.
668 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
669 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
670 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
671 return true;
672
673 return VisitCXXRecordDecl(D);
674}
675
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000676bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000677 // Visit the default argument.
678 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
679 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
680 if (Visit(DefArg->getTypeLoc()))
681 return true;
682
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000683 return false;
684}
685
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000686bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
687 if (Expr *Init = D->getInitExpr())
688 return Visit(MakeCXCursor(Init, StmtParent, TU));
689 return false;
690}
691
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000692bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
693 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
694 if (Visit(TSInfo->getTypeLoc()))
695 return true;
696
697 return false;
698}
699
Douglas Gregorb1373d02010-01-20 20:59:29 +0000700bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000701 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
702 // Visit the function declaration's syntactic components in the order
703 // written. This requires a bit of work.
704 TypeLoc TL = TSInfo->getTypeLoc();
705 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
706
707 // If we have a function declared directly (without the use of a typedef),
708 // visit just the return type. Otherwise, just visit the function's type
709 // now.
710 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
711 (!FTL && Visit(TL)))
712 return true;
713
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000714 // Visit the nested-name-specifier, if present.
715 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
716 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
717 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000718
719 // Visit the declaration name.
720 if (VisitDeclarationNameInfo(ND->getNameInfo()))
721 return true;
722
723 // FIXME: Visit explicitly-specified template arguments!
724
725 // Visit the function parameters, if we have a function type.
726 if (FTL && VisitFunctionTypeLoc(*FTL, true))
727 return true;
728
729 // FIXME: Attributes?
730 }
731
Douglas Gregora59e3902010-01-21 23:27:09 +0000732 if (ND->isThisDeclarationADefinition() &&
733 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
734 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000735
Douglas Gregorb1373d02010-01-20 20:59:29 +0000736 return false;
737}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000738
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000739bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
740 if (VisitDeclaratorDecl(D))
741 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000742
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000743 if (Expr *BitWidth = D->getBitWidth())
744 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000745
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000746 return false;
747}
748
749bool CursorVisitor::VisitVarDecl(VarDecl *D) {
750 if (VisitDeclaratorDecl(D))
751 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000752
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000753 if (Expr *Init = D->getInit())
754 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000755
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000756 return false;
757}
758
Douglas Gregor84b51d72010-09-01 20:16:53 +0000759bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
760 if (VisitDeclaratorDecl(D))
761 return true;
762
763 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
764 if (Expr *DefArg = D->getDefaultArgument())
765 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
766
767 return false;
768}
769
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000770bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
771 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
772 // before visiting these template parameters.
773 if (VisitTemplateParameters(D->getTemplateParameters()))
774 return true;
775
776 return VisitFunctionDecl(D->getTemplatedDecl());
777}
778
Douglas Gregor39d6f072010-08-31 19:02:00 +0000779bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
780 // FIXME: Visit the "outer" template parameter lists on the TagDecl
781 // before visiting these template parameters.
782 if (VisitTemplateParameters(D->getTemplateParameters()))
783 return true;
784
785 return VisitCXXRecordDecl(D->getTemplatedDecl());
786}
787
Douglas Gregor84b51d72010-09-01 20:16:53 +0000788bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
789 if (VisitTemplateParameters(D->getTemplateParameters()))
790 return true;
791
792 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
793 VisitTemplateArgumentLoc(D->getDefaultArgument()))
794 return true;
795
796 return false;
797}
798
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000799bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000800 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
801 if (Visit(TSInfo->getTypeLoc()))
802 return true;
803
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 PEnd = ND->param_end();
806 P != PEnd; ++P) {
807 if (Visit(MakeCXCursor(*P, TU)))
808 return true;
809 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000810
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000811 if (ND->isThisDeclarationADefinition() &&
812 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
813 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000814
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000815 return false;
816}
817
Douglas Gregora59e3902010-01-21 23:27:09 +0000818bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
819 return VisitDeclContext(D);
820}
821
Douglas Gregorb1373d02010-01-20 20:59:29 +0000822bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000823 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
824 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000825 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000826
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000827 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
828 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
829 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000830 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000831 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000832
Douglas Gregora59e3902010-01-21 23:27:09 +0000833 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000834}
835
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000836bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
837 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
838 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
839 E = PID->protocol_end(); I != E; ++I, ++PL)
840 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
841 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000843 return VisitObjCContainerDecl(PID);
844}
845
Ted Kremenek23173d72010-05-18 21:09:07 +0000846bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000847 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
848 return true;
849
Ted Kremenek23173d72010-05-18 21:09:07 +0000850 // FIXME: This implements a workaround with @property declarations also being
851 // installed in the DeclContext for the @interface. Eventually this code
852 // should be removed.
853 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
854 if (!CDecl || !CDecl->IsClassExtension())
855 return false;
856
857 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
858 if (!ID)
859 return false;
860
861 IdentifierInfo *PropertyId = PD->getIdentifier();
862 ObjCPropertyDecl *prevDecl =
863 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
864
865 if (!prevDecl)
866 return false;
867
868 // Visit synthesized methods since they will be skipped when visiting
869 // the @interface.
870 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
871 if (MD->isSynthesized())
872 if (Visit(MakeCXCursor(MD, TU)))
873 return true;
874
875 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
876 if (MD->isSynthesized())
877 if (Visit(MakeCXCursor(MD, TU)))
878 return true;
879
880 return false;
881}
882
Douglas Gregorb1373d02010-01-20 20:59:29 +0000883bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000884 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000885 if (D->getSuperClass() &&
886 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000887 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000888 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000889 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000890
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000891 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
892 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
893 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000894 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000895 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000896
Douglas Gregora59e3902010-01-21 23:27:09 +0000897 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000898}
899
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000900bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
901 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000902}
903
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000904bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000905 // 'ID' could be null when dealing with invalid code.
906 if (ObjCInterfaceDecl *ID = D->getClassInterface())
907 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
908 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000909
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000910 return VisitObjCImplDecl(D);
911}
912
913bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
914#if 0
915 // Issue callbacks for super class.
916 // FIXME: No source location information!
917 if (D->getSuperClass() &&
918 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000919 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000920 TU)))
921 return true;
922#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000923
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000924 return VisitObjCImplDecl(D);
925}
926
927bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
928 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
929 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
930 E = D->protocol_end();
931 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000932 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000933 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000934
935 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000936}
937
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000938bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
939 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
940 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
941 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000942
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000943 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000944}
945
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000946bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
947 return VisitDeclContext(D);
948}
949
Douglas Gregor69319002010-08-31 23:48:11 +0000950bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000951 // Visit nested-name-specifier.
952 if (NestedNameSpecifier *Qualifier = D->getQualifier())
953 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
954 return true;
Douglas Gregor69319002010-08-31 23:48:11 +0000955
956 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
957 D->getTargetNameLoc(), TU));
958}
959
Douglas Gregor7e242562010-09-01 19:52:22 +0000960bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000961 // Visit nested-name-specifier.
962 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
963 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
964 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +0000965
966 // FIXME: Provide a multi-reference of some kind for all of the declarations
967 // that the using declaration refers to. We don't have this kind of cursor
968 // yet.
969
970 return VisitDeclarationNameInfo(D->getNameInfo());
971}
972
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000973bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000974 // Visit nested-name-specifier.
975 if (NestedNameSpecifier *Qualifier = D->getQualifier())
976 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
977 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000978
979 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
980 D->getIdentLocation(), TU));
981}
982
Douglas Gregor7e242562010-09-01 19:52:22 +0000983bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000984 // Visit nested-name-specifier.
985 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
986 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
987 return true;
988
Douglas Gregor7e242562010-09-01 19:52:22 +0000989 return VisitDeclarationNameInfo(D->getNameInfo());
990}
991
992bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
993 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000994 // Visit nested-name-specifier.
995 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
996 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
997 return true;
998
Douglas Gregor7e242562010-09-01 19:52:22 +0000999 return false;
1000}
1001
Douglas Gregor01829d32010-08-31 14:41:23 +00001002bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1003 switch (Name.getName().getNameKind()) {
1004 case clang::DeclarationName::Identifier:
1005 case clang::DeclarationName::CXXLiteralOperatorName:
1006 case clang::DeclarationName::CXXOperatorName:
1007 case clang::DeclarationName::CXXUsingDirective:
1008 return false;
1009
1010 case clang::DeclarationName::CXXConstructorName:
1011 case clang::DeclarationName::CXXDestructorName:
1012 case clang::DeclarationName::CXXConversionFunctionName:
1013 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1014 return Visit(TSInfo->getTypeLoc());
1015 return false;
1016
1017 case clang::DeclarationName::ObjCZeroArgSelector:
1018 case clang::DeclarationName::ObjCOneArgSelector:
1019 case clang::DeclarationName::ObjCMultiArgSelector:
1020 // FIXME: Per-identifier location info?
1021 return false;
1022 }
1023
1024 return false;
1025}
1026
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001027bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1028 SourceRange Range) {
1029 // FIXME: This whole routine is a hack to work around the lack of proper
1030 // source information in nested-name-specifiers (PR5791). Since we do have
1031 // a beginning source location, we can visit the first component of the
1032 // nested-name-specifier, if it's a single-token component.
1033 if (!NNS)
1034 return false;
1035
1036 // Get the first component in the nested-name-specifier.
1037 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1038 NNS = Prefix;
1039
1040 switch (NNS->getKind()) {
1041 case NestedNameSpecifier::Namespace:
1042 // FIXME: The token at this source location might actually have been a
1043 // namespace alias, but we don't model that. Lame!
1044 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1045 TU));
1046
1047 case NestedNameSpecifier::TypeSpec: {
1048 // If the type has a form where we know that the beginning of the source
1049 // range matches up with a reference cursor. Visit the appropriate reference
1050 // cursor.
1051 Type *T = NNS->getAsType();
1052 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1053 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1054 if (const TagType *Tag = dyn_cast<TagType>(T))
1055 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1056 if (const TemplateSpecializationType *TST
1057 = dyn_cast<TemplateSpecializationType>(T))
1058 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1059 break;
1060 }
1061
1062 case NestedNameSpecifier::TypeSpecWithTemplate:
1063 case NestedNameSpecifier::Global:
1064 case NestedNameSpecifier::Identifier:
1065 break;
1066 }
1067
1068 return false;
1069}
1070
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001071bool CursorVisitor::VisitTemplateParameters(
1072 const TemplateParameterList *Params) {
1073 if (!Params)
1074 return false;
1075
1076 for (TemplateParameterList::const_iterator P = Params->begin(),
1077 PEnd = Params->end();
1078 P != PEnd; ++P) {
1079 if (Visit(MakeCXCursor(*P, TU)))
1080 return true;
1081 }
1082
1083 return false;
1084}
1085
Douglas Gregor0b36e612010-08-31 20:37:03 +00001086bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1087 switch (Name.getKind()) {
1088 case TemplateName::Template:
1089 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1090
1091 case TemplateName::OverloadedTemplate:
1092 // FIXME: We need a way to return multiple lookup results in a single
1093 // cursor.
1094 return false;
1095
1096 case TemplateName::DependentTemplate:
1097 // FIXME: Visit nested-name-specifier.
1098 return false;
1099
1100 case TemplateName::QualifiedTemplate:
1101 // FIXME: Visit nested-name-specifier.
1102 return Visit(MakeCursorTemplateRef(
1103 Name.getAsQualifiedTemplateName()->getDecl(),
1104 Loc, TU));
1105 }
1106
1107 return false;
1108}
1109
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001110bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1111 switch (TAL.getArgument().getKind()) {
1112 case TemplateArgument::Null:
1113 case TemplateArgument::Integral:
1114 return false;
1115
1116 case TemplateArgument::Pack:
1117 // FIXME: Implement when variadic templates come along.
1118 return false;
1119
1120 case TemplateArgument::Type:
1121 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1122 return Visit(TSInfo->getTypeLoc());
1123 return false;
1124
1125 case TemplateArgument::Declaration:
1126 if (Expr *E = TAL.getSourceDeclExpression())
1127 return Visit(MakeCXCursor(E, StmtParent, TU));
1128 return false;
1129
1130 case TemplateArgument::Expression:
1131 if (Expr *E = TAL.getSourceExpression())
1132 return Visit(MakeCXCursor(E, StmtParent, TU));
1133 return false;
1134
1135 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001136 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1137 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001138 }
1139
1140 return false;
1141}
1142
Ted Kremeneka0536d82010-05-07 01:04:29 +00001143bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1144 return VisitDeclContext(D);
1145}
1146
Douglas Gregor01829d32010-08-31 14:41:23 +00001147bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1148 return Visit(TL.getUnqualifiedLoc());
1149}
1150
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001151bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1152 ASTContext &Context = TU->getASTContext();
1153
1154 // Some builtin types (such as Objective-C's "id", "sel", and
1155 // "Class") have associated declarations. Create cursors for those.
1156 QualType VisitType;
1157 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001158 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001159 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001160 case BuiltinType::Char_U:
1161 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001162 case BuiltinType::Char16:
1163 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001164 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001165 case BuiltinType::UInt:
1166 case BuiltinType::ULong:
1167 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001168 case BuiltinType::UInt128:
1169 case BuiltinType::Char_S:
1170 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001171 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001172 case BuiltinType::Short:
1173 case BuiltinType::Int:
1174 case BuiltinType::Long:
1175 case BuiltinType::LongLong:
1176 case BuiltinType::Int128:
1177 case BuiltinType::Float:
1178 case BuiltinType::Double:
1179 case BuiltinType::LongDouble:
1180 case BuiltinType::NullPtr:
1181 case BuiltinType::Overload:
1182 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001183 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001184
1185 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001186 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001187
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001188 case BuiltinType::ObjCId:
1189 VisitType = Context.getObjCIdType();
1190 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001191
1192 case BuiltinType::ObjCClass:
1193 VisitType = Context.getObjCClassType();
1194 break;
1195
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001196 case BuiltinType::ObjCSel:
1197 VisitType = Context.getObjCSelType();
1198 break;
1199 }
1200
1201 if (!VisitType.isNull()) {
1202 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001203 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001204 TU));
1205 }
1206
1207 return false;
1208}
1209
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001210bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1211 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1212}
1213
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001214bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1215 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1216}
1217
1218bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1219 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1220}
1221
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001222bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1223 // FIXME: We can't visit the template template parameter, but there's
1224 // no context information with which we can match up the depth/index in the
1225 // type to the appropriate
1226 return false;
1227}
1228
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001229bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1230 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1231 return true;
1232
John McCallc12c5bb2010-05-15 11:32:37 +00001233 return false;
1234}
1235
1236bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1237 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1238 return true;
1239
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001240 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1241 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1242 TU)))
1243 return true;
1244 }
1245
1246 return false;
1247}
1248
1249bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001250 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001251}
1252
1253bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1254 return Visit(TL.getPointeeLoc());
1255}
1256
1257bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1258 return Visit(TL.getPointeeLoc());
1259}
1260
1261bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1262 return Visit(TL.getPointeeLoc());
1263}
1264
1265bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001266 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001267}
1268
1269bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001270 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001271}
1272
Douglas Gregor01829d32010-08-31 14:41:23 +00001273bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1274 bool SkipResultType) {
1275 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001276 return true;
1277
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001278 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001279 if (Decl *D = TL.getArg(I))
1280 if (Visit(MakeCXCursor(D, TU)))
1281 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001282
1283 return false;
1284}
1285
1286bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1287 if (Visit(TL.getElementLoc()))
1288 return true;
1289
1290 if (Expr *Size = TL.getSizeExpr())
1291 return Visit(MakeCXCursor(Size, StmtParent, TU));
1292
1293 return false;
1294}
1295
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001296bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1297 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001298 // Visit the template name.
1299 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1300 TL.getTemplateNameLoc()))
1301 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001302
1303 // Visit the template arguments.
1304 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1305 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1306 return true;
1307
1308 return false;
1309}
1310
Douglas Gregor2332c112010-01-21 20:48:56 +00001311bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1312 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1313}
1314
1315bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1316 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1317 return Visit(TSInfo->getTypeLoc());
1318
1319 return false;
1320}
1321
Douglas Gregora59e3902010-01-21 23:27:09 +00001322bool CursorVisitor::VisitStmt(Stmt *S) {
1323 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1324 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001325 if (Stmt *C = *Child)
1326 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1327 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001328 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001329
Douglas Gregora59e3902010-01-21 23:27:09 +00001330 return false;
1331}
1332
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001333bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1334 // Specially handle CaseStmts because they can be nested, e.g.:
1335 //
1336 // case 1:
1337 // case 2:
1338 //
1339 // In this case the second CaseStmt is the child of the first. Walking
1340 // these recursively can blow out the stack.
1341 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1342 while (true) {
1343 // Set the Parent field to Cursor, then back to its old value once we're
1344 // done.
1345 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1346
1347 if (Stmt *LHS = S->getLHS())
1348 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1349 return true;
1350 if (Stmt *RHS = S->getRHS())
1351 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1352 return true;
1353 if (Stmt *SubStmt = S->getSubStmt()) {
1354 if (!isa<CaseStmt>(SubStmt))
1355 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1356
1357 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1358 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1359 Cursor = MakeCXCursor(CS, StmtParent, TU);
1360 if (RegionOfInterest.isValid()) {
1361 SourceRange Range = CS->getSourceRange();
1362 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1363 return false;
1364 }
1365
1366 switch (Visitor(Cursor, Parent, ClientData)) {
1367 case CXChildVisit_Break: return true;
1368 case CXChildVisit_Continue: return false;
1369 case CXChildVisit_Recurse:
1370 // Perform tail-recursion manually.
1371 S = CS;
1372 continue;
1373 }
1374 }
1375 return false;
1376 }
1377}
1378
Douglas Gregora59e3902010-01-21 23:27:09 +00001379bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1380 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1381 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001382 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001383 return true;
1384 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001385
Douglas Gregora59e3902010-01-21 23:27:09 +00001386 return false;
1387}
1388
Douglas Gregorf5bab412010-01-22 01:00:11 +00001389bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1390 if (VarDecl *Var = S->getConditionVariable()) {
1391 if (Visit(MakeCXCursor(Var, TU)))
1392 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001393 }
1394
Douglas Gregor263b47b2010-01-25 16:12:32 +00001395 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1396 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001397 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1398 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001399 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1400 return true;
1401
1402 return false;
1403}
1404
1405bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1406 if (VarDecl *Var = S->getConditionVariable()) {
1407 if (Visit(MakeCXCursor(Var, TU)))
1408 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001409 }
1410
Douglas Gregor263b47b2010-01-25 16:12:32 +00001411 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1412 return true;
1413 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1414 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001415
Douglas Gregor263b47b2010-01-25 16:12:32 +00001416 return false;
1417}
1418
1419bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1420 if (VarDecl *Var = S->getConditionVariable()) {
1421 if (Visit(MakeCXCursor(Var, TU)))
1422 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001423 }
1424
Douglas Gregor263b47b2010-01-25 16:12:32 +00001425 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1426 return true;
1427 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001428 return true;
1429
Douglas Gregor263b47b2010-01-25 16:12:32 +00001430 return false;
1431}
1432
1433bool CursorVisitor::VisitForStmt(ForStmt *S) {
1434 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1435 return true;
1436 if (VarDecl *Var = S->getConditionVariable()) {
1437 if (Visit(MakeCXCursor(Var, TU)))
1438 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001439 }
1440
Douglas Gregor263b47b2010-01-25 16:12:32 +00001441 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1442 return true;
1443 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1444 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001445 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1446 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001447
Douglas Gregorf5bab412010-01-22 01:00:11 +00001448 return false;
1449}
1450
Douglas Gregor8947a752010-09-02 20:35:02 +00001451bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1452 // Visit nested-name-specifier, if present.
1453 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1454 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1455 return true;
1456
1457 // Visit declaration name.
1458 if (VisitDeclarationNameInfo(E->getNameInfo()))
1459 return true;
1460
1461 // Visit explicitly-specified template arguments.
1462 if (E->hasExplicitTemplateArgs()) {
1463 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1464 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1465 *ArgEnd = Arg + Args.NumTemplateArgs;
1466 Arg != ArgEnd; ++Arg)
1467 if (VisitTemplateArgumentLoc(*Arg))
1468 return true;
1469 }
1470
1471 return false;
1472}
1473
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001474bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1475 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1476 return true;
1477
1478 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1479 return true;
1480
1481 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1482 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1483 return true;
1484
1485 return false;
1486}
1487
Ted Kremenek3064ef92010-08-27 21:34:58 +00001488bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1489 if (D->isDefinition()) {
1490 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1491 E = D->bases_end(); I != E; ++I) {
1492 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1493 return true;
1494 }
1495 }
1496
1497 return VisitTagDecl(D);
1498}
1499
1500
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001501bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1502 return Visit(B->getBlockDecl());
1503}
1504
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001505bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1506 // FIXME: Visit fields as well?
1507 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1508 return true;
1509
1510 return VisitExpr(E);
1511}
1512
Douglas Gregor336fd812010-01-23 00:40:08 +00001513bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1514 if (E->isArgumentType()) {
1515 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1516 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001517
Douglas Gregor336fd812010-01-23 00:40:08 +00001518 return false;
1519 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001520
Douglas Gregor336fd812010-01-23 00:40:08 +00001521 return VisitExpr(E);
1522}
1523
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001524bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1525 // Visit the base expression.
1526 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1527 return true;
1528
1529 // Visit the nested-name-specifier
1530 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1531 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1532 return true;
1533
1534 // Visit the declaration name.
1535 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1536 return true;
1537
1538 // Visit the explicitly-specified template arguments, if any.
1539 if (E->hasExplicitTemplateArgs()) {
1540 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1541 *ArgEnd = Arg + E->getNumTemplateArgs();
1542 Arg != ArgEnd;
1543 ++Arg) {
1544 if (VisitTemplateArgumentLoc(*Arg))
1545 return true;
1546 }
1547 }
1548
1549 return false;
1550}
1551
Douglas Gregor336fd812010-01-23 00:40:08 +00001552bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1553 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1554 if (Visit(TSInfo->getTypeLoc()))
1555 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001556
Douglas Gregor336fd812010-01-23 00:40:08 +00001557 return VisitCastExpr(E);
1558}
1559
1560bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1561 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1562 if (Visit(TSInfo->getTypeLoc()))
1563 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001564
Douglas Gregor336fd812010-01-23 00:40:08 +00001565 return VisitExpr(E);
1566}
1567
Douglas Gregor648220e2010-08-10 15:02:34 +00001568bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1569 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1570 Visit(E->getArgTInfo2()->getTypeLoc());
1571}
1572
1573bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1574 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1575 return true;
1576
1577 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1578}
1579
Douglas Gregor94802292010-09-02 21:20:16 +00001580bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1581 if (E->isTypeOperand()) {
1582 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1583 return Visit(TSInfo->getTypeLoc());
1584
1585 return false;
1586 }
1587
1588 return VisitExpr(E);
1589}
1590
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001591bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1592 // Visit base expression.
1593 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1594 return true;
1595
1596 // Visit the nested-name-specifier.
1597 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1598 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1599 return true;
1600
1601 // Visit the scope type that looks disturbingly like the nested-name-specifier
1602 // but isn't.
1603 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1604 if (Visit(TSInfo->getTypeLoc()))
1605 return true;
1606
1607 // Visit the name of the type being destroyed.
1608 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1609 if (Visit(TSInfo->getTypeLoc()))
1610 return true;
1611
1612 return false;
1613}
1614
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001615bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001616 // Visit the nested-name-specifier.
1617 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1618 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1619 return true;
1620
1621 // Visit the declaration name.
1622 if (VisitDeclarationNameInfo(E->getNameInfo()))
1623 return true;
1624
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001625 // Visit the explicitly-specified template arguments.
1626 if (const ExplicitTemplateArgumentList *ArgList
1627 = E->getOptionalExplicitTemplateArgs()) {
1628 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1629 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1630 Arg != ArgEnd; ++Arg) {
1631 if (VisitTemplateArgumentLoc(*Arg))
1632 return true;
1633 }
1634 }
1635
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001636 // FIXME: We don't have a way to visit all of the declarations referenced
1637 // here.
1638 return false;
1639}
1640
Douglas Gregorbfebed22010-09-03 17:24:10 +00001641bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1642 DependentScopeDeclRefExpr *E) {
1643 // Visit the nested-name-specifier.
1644 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1645 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1646 return true;
1647
1648 // Visit the declaration name.
1649 if (VisitDeclarationNameInfo(E->getNameInfo()))
1650 return true;
1651
1652 // Visit the explicitly-specified template arguments.
1653 if (const ExplicitTemplateArgumentList *ArgList
1654 = E->getOptionalExplicitTemplateArgs()) {
1655 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1656 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1657 Arg != ArgEnd; ++Arg) {
1658 if (VisitTemplateArgumentLoc(*Arg))
1659 return true;
1660 }
1661 }
1662
1663 return false;
1664}
1665
Douglas Gregor25d63622010-09-03 17:35:34 +00001666bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1667 CXXDependentScopeMemberExpr *E) {
1668 // Visit the base expression, if there is one.
1669 if (!E->isImplicitAccess() &&
1670 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1671 return true;
1672
1673 // Visit the nested-name-specifier.
1674 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1675 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1676 return true;
1677
1678 // Visit the declaration name.
1679 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1680 return true;
1681
1682 // Visit the explicitly-specified template arguments.
1683 if (const ExplicitTemplateArgumentList *ArgList
1684 = E->getOptionalExplicitTemplateArgs()) {
1685 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1686 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1687 Arg != ArgEnd; ++Arg) {
1688 if (VisitTemplateArgumentLoc(*Arg))
1689 return true;
1690 }
1691 }
1692
1693 return false;
1694}
1695
1696
Douglas Gregorc2350e52010-03-08 16:40:19 +00001697bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001698 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1699 if (Visit(TSInfo->getTypeLoc()))
1700 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001701
1702 return VisitExpr(E);
1703}
1704
Douglas Gregor81d34662010-04-20 15:39:42 +00001705bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1706 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1707}
1708
1709
Ted Kremenek09dfa372010-02-18 05:46:33 +00001710bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001711 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1712 i != e; ++i)
1713 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001714 return true;
1715
1716 return false;
1717}
1718
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001719extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001720CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1721 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001722 // We use crash recovery to make some of our APIs more reliable, implicitly
1723 // enable it.
1724 llvm::CrashRecoveryContext::Enable();
1725
Douglas Gregora030b7c2010-01-22 20:35:53 +00001726 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001727 if (excludeDeclarationsFromPCH)
1728 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001729 if (displayDiagnostics)
1730 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001731 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001732}
1733
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001734void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001735 if (CIdx)
1736 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001737 if (getenv("LIBCLANG_TIMING"))
1738 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001739}
1740
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001741void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001742 if (CIdx) {
1743 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1744 CXXIdx->setUseExternalASTGeneration(value);
1745 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001746}
1747
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001748CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001749 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001750 if (!CIdx)
1751 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001752
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001753 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001754
Douglas Gregor28019772010-04-05 23:52:57 +00001755 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001756 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001757 CXXIdx->getOnlyLocalDecls(),
1758 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001759}
1760
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001761unsigned clang_defaultEditingTranslationUnitOptions() {
1762 return CXTranslationUnit_PrecompiledPreamble;
1763}
1764
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001765CXTranslationUnit
1766clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1767 const char *source_filename,
1768 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001769 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001770 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001771 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001772 return clang_parseTranslationUnit(CIdx, source_filename,
1773 command_line_args, num_command_line_args,
1774 unsaved_files, num_unsaved_files,
1775 CXTranslationUnit_DetailedPreprocessingRecord);
1776}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001777
1778struct ParseTranslationUnitInfo {
1779 CXIndex CIdx;
1780 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001781 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001782 int num_command_line_args;
1783 struct CXUnsavedFile *unsaved_files;
1784 unsigned num_unsaved_files;
1785 unsigned options;
1786 CXTranslationUnit result;
1787};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001788static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001789 ParseTranslationUnitInfo *PTUI =
1790 static_cast<ParseTranslationUnitInfo*>(UserData);
1791 CXIndex CIdx = PTUI->CIdx;
1792 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001793 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001794 int num_command_line_args = PTUI->num_command_line_args;
1795 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1796 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1797 unsigned options = PTUI->options;
1798 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001799
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001800 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001801 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001802
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001803 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1804
Douglas Gregor44c181a2010-07-23 00:33:23 +00001805 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001806 bool CompleteTranslationUnit
1807 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001808 bool CacheCodeCompetionResults
1809 = options & CXTranslationUnit_CacheCompletionResults;
1810
Douglas Gregor5352ac02010-01-28 00:27:43 +00001811 // Configure the diagnostics.
1812 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001813 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1814 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001815
Douglas Gregor4db64a42010-01-23 00:14:00 +00001816 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1817 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001818 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001819 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001820 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001821 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1822 Buffer));
1823 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001824
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001825 if (!CXXIdx->getUseExternalASTGeneration()) {
1826 llvm::SmallVector<const char *, 16> Args;
1827
1828 // The 'source_filename' argument is optional. If the caller does not
1829 // specify it then it is assumed that the source file is specified
1830 // in the actual argument list.
1831 if (source_filename)
1832 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001833
1834 // Since the Clang C library is primarily used by batch tools dealing with
1835 // (often very broken) source code, where spell-checking can have a
1836 // significant negative impact on performance (particularly when
1837 // precompiled headers are involved), we disable it by default.
1838 // Note that we place this argument early in the list, so that it can be
1839 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001840 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001841
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001842 Args.insert(Args.end(), command_line_args,
1843 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001844
Douglas Gregor44c181a2010-07-23 00:33:23 +00001845 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001846 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1847 Args.push_back("-Xclang");
1848 Args.push_back("-detailed-preprocessing-record");
1849 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001850
Douglas Gregor5352ac02010-01-28 00:27:43 +00001851 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001852
Ted Kremenek29b72842010-01-07 22:49:05 +00001853#ifdef USE_CRASHTRACER
1854 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001855#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001856
Daniel Dunbar94220972009-12-05 02:17:18 +00001857 llvm::OwningPtr<ASTUnit> Unit(
1858 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001859 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001860 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001861 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001862 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001863 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001864 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001865 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001866 CompleteTranslationUnit,
1867 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001868
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001869 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001870 // Make sure to check that 'Unit' is non-NULL.
1871 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001872 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1873 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001874 D != DEnd; ++D) {
1875 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001876 CXString Msg = clang_formatDiagnostic(&Diag,
1877 clang_defaultDiagnosticDisplayOptions());
1878 fprintf(stderr, "%s\n", clang_getCString(Msg));
1879 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001880 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001881#ifdef LLVM_ON_WIN32
1882 // On Windows, force a flush, since there may be multiple copies of
1883 // stderr and stdout in the file system, all with different buffers
1884 // but writing to the same device.
1885 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001886#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001887 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001888 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001889
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001890 PTUI->result = Unit.take();
1891 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001892 }
1893
Ted Kremenek139ba862009-10-22 00:03:57 +00001894 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001895 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001896
Ted Kremenek139ba862009-10-22 00:03:57 +00001897 // First add the complete path to the 'clang' executable.
1898 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001899 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001900
Ted Kremenek139ba862009-10-22 00:03:57 +00001901 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001902 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001903
Ted Kremenek139ba862009-10-22 00:03:57 +00001904 // The 'source_filename' argument is optional. If the caller does not
1905 // specify it then it is assumed that the source file is specified
1906 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001907 if (source_filename)
1908 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001909
Steve Naroff37b5ac22009-10-15 20:50:09 +00001910 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001911 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001912 char astTmpFile[L_tmpnam];
1913 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001914
1915 // Since the Clang C library is primarily used by batch tools dealing with
1916 // (often very broken) source code, where spell-checking can have a
1917 // significant negative impact on performance (particularly when
1918 // precompiled headers are involved), we disable it by default.
1919 // Note that we place this argument early in the list, so that it can be
1920 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001921 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001922
Douglas Gregor4db64a42010-01-23 00:14:00 +00001923 // Remap any unsaved files to temporary files.
1924 std::vector<llvm::sys::Path> TemporaryFiles;
1925 std::vector<std::string> RemapArgs;
1926 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001927 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001928
Douglas Gregor4db64a42010-01-23 00:14:00 +00001929 // The pointers into the elements of RemapArgs are stable because we
1930 // won't be adding anything to RemapArgs after this point.
1931 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1932 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001933
Ted Kremenek139ba862009-10-22 00:03:57 +00001934 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1935 for (int i = 0; i < num_command_line_args; ++i)
1936 if (const char *arg = command_line_args[i]) {
1937 if (strcmp(arg, "-o") == 0) {
1938 ++i; // Also skip the matching argument.
1939 continue;
1940 }
1941 if (strcmp(arg, "-emit-ast") == 0 ||
1942 strcmp(arg, "-c") == 0 ||
1943 strcmp(arg, "-fsyntax-only") == 0) {
1944 continue;
1945 }
1946
1947 // Keep the argument.
1948 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001949 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001950
Douglas Gregord93256e2010-01-28 06:00:51 +00001951 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001952 char tmpFileResults[L_tmpnam];
1953 char *tmpResultsFileName = tmpnam(tmpFileResults);
1954 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001955 TemporaryFiles.push_back(DiagnosticsFile);
1956 argv.push_back("-fdiagnostics-binary");
1957
Douglas Gregor44c181a2010-07-23 00:33:23 +00001958 // Do we need the detailed preprocessing record?
1959 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1960 argv.push_back("-Xclang");
1961 argv.push_back("-detailed-preprocessing-record");
1962 }
1963
Ted Kremenek139ba862009-10-22 00:03:57 +00001964 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001965 argv.push_back(NULL);
1966
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001967 // Invoke 'clang'.
1968 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1969 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001970 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001971 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1972 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001973 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001974 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001975 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001976
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001977 if (!ErrMsg.empty()) {
1978 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001979 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001980 I != E; ++I) {
1981 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001982 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001983 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001984 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001985
Daniel Dunbar32141c82010-02-23 20:23:45 +00001986 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001987 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001988
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001989 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001990 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001991 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001992 RemappedFiles.size(),
1993 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001994 if (ATU) {
1995 LoadSerializedDiagnostics(DiagnosticsFile,
1996 num_unsaved_files, unsaved_files,
1997 ATU->getFileManager(),
1998 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001999 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002000 } else if (CXXIdx->getDisplayDiagnostics()) {
2001 // We failed to load the ASTUnit, but we can still deserialize the
2002 // diagnostics and emit them.
2003 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00002004 Diagnostic Diag;
2005 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002006 // FIXME: Faked LangOpts!
2007 LangOptions LangOpts;
2008 llvm::SmallVector<StoredDiagnostic, 4> Diags;
2009 LoadSerializedDiagnostics(DiagnosticsFile,
2010 num_unsaved_files, unsaved_files,
2011 FileMgr, SourceMgr, Diags);
2012 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
2013 DEnd = Diags.end();
2014 D != DEnd; ++D) {
2015 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00002016 CXString Msg = clang_formatDiagnostic(&Diag,
2017 clang_defaultDiagnosticDisplayOptions());
2018 fprintf(stderr, "%s\n", clang_getCString(Msg));
2019 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002020 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002021
2022#ifdef LLVM_ON_WIN32
2023 // On Windows, force a flush, since there may be multiple copies of
2024 // stderr and stdout in the file system, all with different buffers
2025 // but writing to the same device.
2026 fflush(stderr);
2027#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00002028 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002029
Douglas Gregor313e26c2010-02-18 23:35:40 +00002030 if (ATU) {
2031 // Make the translation unit responsible for destroying all temporary files.
2032 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2033 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002034 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00002035 } else {
2036 // Destroy all of the temporary files now; they can't be referenced any
2037 // longer.
2038 llvm::sys::Path(astTmpFile).eraseFromDisk();
2039 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2040 TemporaryFiles[i].eraseFromDisk();
2041 }
2042
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002043 PTUI->result = ATU;
2044}
2045CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2046 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002047 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002048 int num_command_line_args,
2049 struct CXUnsavedFile *unsaved_files,
2050 unsigned num_unsaved_files,
2051 unsigned options) {
2052 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2053 num_command_line_args, unsaved_files, num_unsaved_files,
2054 options, 0 };
2055 llvm::CrashRecoveryContext CRC;
2056
2057 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002058 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2059 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2060 fprintf(stderr, " 'command_line_args' : [");
2061 for (int i = 0; i != num_command_line_args; ++i) {
2062 if (i)
2063 fprintf(stderr, ", ");
2064 fprintf(stderr, "'%s'", command_line_args[i]);
2065 }
2066 fprintf(stderr, "],\n");
2067 fprintf(stderr, " 'unsaved_files' : [");
2068 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2069 if (i)
2070 fprintf(stderr, ", ");
2071 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2072 unsaved_files[i].Length);
2073 }
2074 fprintf(stderr, "],\n");
2075 fprintf(stderr, " 'options' : %d,\n", options);
2076 fprintf(stderr, "}\n");
2077
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002078 return 0;
2079 }
2080
2081 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002082}
2083
Douglas Gregor19998442010-08-13 15:35:05 +00002084unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2085 return CXSaveTranslationUnit_None;
2086}
2087
2088int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2089 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002090 if (!TU)
2091 return 1;
2092
2093 return static_cast<ASTUnit *>(TU)->Save(FileName);
2094}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002095
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002096void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002097 if (CTUnit) {
2098 // If the translation unit has been marked as unsafe to free, just discard
2099 // it.
2100 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2101 return;
2102
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002103 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002104 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002105}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002106
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002107unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2108 return CXReparse_None;
2109}
2110
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002111struct ReparseTranslationUnitInfo {
2112 CXTranslationUnit TU;
2113 unsigned num_unsaved_files;
2114 struct CXUnsavedFile *unsaved_files;
2115 unsigned options;
2116 int result;
2117};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002118static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002119 ReparseTranslationUnitInfo *RTUI =
2120 static_cast<ReparseTranslationUnitInfo*>(UserData);
2121 CXTranslationUnit TU = RTUI->TU;
2122 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2123 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2124 unsigned options = RTUI->options;
2125 (void) options;
2126 RTUI->result = 1;
2127
Douglas Gregorabc563f2010-07-19 21:46:24 +00002128 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002129 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002130
2131 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2132 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2133 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2134 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002135 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002136 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2137 Buffer));
2138 }
2139
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002140 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
2141 RemappedFiles.size()))
2142 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002143}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002144int clang_reparseTranslationUnit(CXTranslationUnit TU,
2145 unsigned num_unsaved_files,
2146 struct CXUnsavedFile *unsaved_files,
2147 unsigned options) {
2148 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2149 options, 0 };
2150 llvm::CrashRecoveryContext CRC;
2151
2152 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002153 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002154 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2155 return 1;
2156 }
2157
2158 return RTUI.result;
2159}
2160
Douglas Gregordf95a132010-08-09 20:45:32 +00002161
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002162CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002163 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002164 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002165
Steve Naroff77accc12009-09-03 18:19:54 +00002166 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002167 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002168}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002169
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002170CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002171 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002172 return Result;
2173}
2174
Ted Kremenekfb480492010-01-13 21:46:36 +00002175} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002176
Ted Kremenekfb480492010-01-13 21:46:36 +00002177//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002178// CXSourceLocation and CXSourceRange Operations.
2179//===----------------------------------------------------------------------===//
2180
Douglas Gregorb9790342010-01-22 21:44:22 +00002181extern "C" {
2182CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002183 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002184 return Result;
2185}
2186
2187unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002188 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2189 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2190 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002191}
2192
2193CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2194 CXFile file,
2195 unsigned line,
2196 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002197 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002198 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002199
Douglas Gregorb9790342010-01-22 21:44:22 +00002200 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2201 SourceLocation SLoc
2202 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002203 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002204 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002205
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002206 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002207}
2208
Douglas Gregor5352ac02010-01-28 00:27:43 +00002209CXSourceRange clang_getNullRange() {
2210 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2211 return Result;
2212}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002213
Douglas Gregor5352ac02010-01-28 00:27:43 +00002214CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2215 if (begin.ptr_data[0] != end.ptr_data[0] ||
2216 begin.ptr_data[1] != end.ptr_data[1])
2217 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002218
2219 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002220 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002221 return Result;
2222}
2223
Douglas Gregor46766dc2010-01-26 19:19:08 +00002224void clang_getInstantiationLocation(CXSourceLocation location,
2225 CXFile *file,
2226 unsigned *line,
2227 unsigned *column,
2228 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002229 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2230
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002231 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002232 if (file)
2233 *file = 0;
2234 if (line)
2235 *line = 0;
2236 if (column)
2237 *column = 0;
2238 if (offset)
2239 *offset = 0;
2240 return;
2241 }
2242
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002243 const SourceManager &SM =
2244 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002245 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002246
2247 if (file)
2248 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2249 if (line)
2250 *line = SM.getInstantiationLineNumber(InstLoc);
2251 if (column)
2252 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002253 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002254 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002255}
2256
Douglas Gregor1db19de2010-01-19 21:36:55 +00002257CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002258 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002259 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002260 return Result;
2261}
2262
2263CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002264 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002265 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002266 return Result;
2267}
2268
Douglas Gregorb9790342010-01-22 21:44:22 +00002269} // end: extern "C"
2270
Douglas Gregor1db19de2010-01-19 21:36:55 +00002271//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002272// CXFile Operations.
2273//===----------------------------------------------------------------------===//
2274
2275extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002276CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002277 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002278 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002279
Steve Naroff88145032009-10-27 14:35:18 +00002280 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002281 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002282}
2283
2284time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002285 if (!SFile)
2286 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002287
Steve Naroff88145032009-10-27 14:35:18 +00002288 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2289 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002290}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002291
Douglas Gregorb9790342010-01-22 21:44:22 +00002292CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2293 if (!tu)
2294 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002295
Douglas Gregorb9790342010-01-22 21:44:22 +00002296 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002297
Douglas Gregorb9790342010-01-22 21:44:22 +00002298 FileManager &FMgr = CXXUnit->getFileManager();
2299 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2300 return const_cast<FileEntry *>(File);
2301}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002302
Ted Kremenekfb480492010-01-13 21:46:36 +00002303} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002304
Ted Kremenekfb480492010-01-13 21:46:36 +00002305//===----------------------------------------------------------------------===//
2306// CXCursor Operations.
2307//===----------------------------------------------------------------------===//
2308
Ted Kremenekfb480492010-01-13 21:46:36 +00002309static Decl *getDeclFromExpr(Stmt *E) {
2310 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2311 return RefExpr->getDecl();
2312 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2313 return ME->getMemberDecl();
2314 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2315 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002316
Ted Kremenekfb480492010-01-13 21:46:36 +00002317 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2318 return getDeclFromExpr(CE->getCallee());
2319 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2320 return getDeclFromExpr(CE->getSubExpr());
2321 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2322 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002323
Ted Kremenekfb480492010-01-13 21:46:36 +00002324 return 0;
2325}
2326
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002327static SourceLocation getLocationFromExpr(Expr *E) {
2328 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2329 return /*FIXME:*/Msg->getLeftLoc();
2330 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2331 return DRE->getLocation();
2332 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2333 return Member->getMemberLoc();
2334 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2335 return Ivar->getLocation();
2336 return E->getLocStart();
2337}
2338
Ted Kremenekfb480492010-01-13 21:46:36 +00002339extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002340
2341unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002342 CXCursorVisitor visitor,
2343 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002344 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002345
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002346 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2347 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002348 return CursorVis.VisitChildren(parent);
2349}
2350
Douglas Gregor78205d42010-01-20 21:45:58 +00002351static CXString getDeclSpelling(Decl *D) {
2352 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2353 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002354 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002355
Douglas Gregor78205d42010-01-20 21:45:58 +00002356 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002357 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002358
Douglas Gregor78205d42010-01-20 21:45:58 +00002359 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2360 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2361 // and returns different names. NamedDecl returns the class name and
2362 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002363 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002364
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002365 if (isa<UsingDirectiveDecl>(D))
2366 return createCXString("");
2367
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002368 llvm::SmallString<1024> S;
2369 llvm::raw_svector_ostream os(S);
2370 ND->printName(os);
2371
2372 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002373}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002374
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002375CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002376 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002377 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002378
Steve Narofff334b4e2009-09-02 18:26:48 +00002379 if (clang_isReference(C.kind)) {
2380 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002381 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002382 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002383 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002384 }
2385 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002386 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002387 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002388 }
2389 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002390 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002391 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002392 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002393 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002394 case CXCursor_CXXBaseSpecifier: {
2395 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2396 return createCXString(B->getType().getAsString());
2397 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002398 case CXCursor_TypeRef: {
2399 TypeDecl *Type = getCursorTypeRef(C).first;
2400 assert(Type && "Missing type decl");
2401
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002402 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2403 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002404 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002405 case CXCursor_TemplateRef: {
2406 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002407 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002408
2409 return createCXString(Template->getNameAsString());
2410 }
Douglas Gregor69319002010-08-31 23:48:11 +00002411
2412 case CXCursor_NamespaceRef: {
2413 NamedDecl *NS = getCursorNamespaceRef(C).first;
2414 assert(NS && "Missing namespace decl");
2415
2416 return createCXString(NS->getNameAsString());
2417 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002418
Daniel Dunbaracca7252009-11-30 20:42:49 +00002419 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002420 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002421 }
2422 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002423
2424 if (clang_isExpression(C.kind)) {
2425 Decl *D = getDeclFromExpr(getCursorExpr(C));
2426 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002427 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002428 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002429 }
2430
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002431 if (C.kind == CXCursor_MacroInstantiation)
2432 return createCXString(getCursorMacroInstantiation(C)->getName()
2433 ->getNameStart());
2434
Douglas Gregor572feb22010-03-18 18:04:21 +00002435 if (C.kind == CXCursor_MacroDefinition)
2436 return createCXString(getCursorMacroDefinition(C)->getName()
2437 ->getNameStart());
2438
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002439 if (clang_isDeclaration(C.kind))
2440 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002441
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002442 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002443}
2444
Ted Kremeneke68fff62010-02-17 00:41:32 +00002445CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002446 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002447 case CXCursor_FunctionDecl:
2448 return createCXString("FunctionDecl");
2449 case CXCursor_TypedefDecl:
2450 return createCXString("TypedefDecl");
2451 case CXCursor_EnumDecl:
2452 return createCXString("EnumDecl");
2453 case CXCursor_EnumConstantDecl:
2454 return createCXString("EnumConstantDecl");
2455 case CXCursor_StructDecl:
2456 return createCXString("StructDecl");
2457 case CXCursor_UnionDecl:
2458 return createCXString("UnionDecl");
2459 case CXCursor_ClassDecl:
2460 return createCXString("ClassDecl");
2461 case CXCursor_FieldDecl:
2462 return createCXString("FieldDecl");
2463 case CXCursor_VarDecl:
2464 return createCXString("VarDecl");
2465 case CXCursor_ParmDecl:
2466 return createCXString("ParmDecl");
2467 case CXCursor_ObjCInterfaceDecl:
2468 return createCXString("ObjCInterfaceDecl");
2469 case CXCursor_ObjCCategoryDecl:
2470 return createCXString("ObjCCategoryDecl");
2471 case CXCursor_ObjCProtocolDecl:
2472 return createCXString("ObjCProtocolDecl");
2473 case CXCursor_ObjCPropertyDecl:
2474 return createCXString("ObjCPropertyDecl");
2475 case CXCursor_ObjCIvarDecl:
2476 return createCXString("ObjCIvarDecl");
2477 case CXCursor_ObjCInstanceMethodDecl:
2478 return createCXString("ObjCInstanceMethodDecl");
2479 case CXCursor_ObjCClassMethodDecl:
2480 return createCXString("ObjCClassMethodDecl");
2481 case CXCursor_ObjCImplementationDecl:
2482 return createCXString("ObjCImplementationDecl");
2483 case CXCursor_ObjCCategoryImplDecl:
2484 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002485 case CXCursor_CXXMethod:
2486 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002487 case CXCursor_UnexposedDecl:
2488 return createCXString("UnexposedDecl");
2489 case CXCursor_ObjCSuperClassRef:
2490 return createCXString("ObjCSuperClassRef");
2491 case CXCursor_ObjCProtocolRef:
2492 return createCXString("ObjCProtocolRef");
2493 case CXCursor_ObjCClassRef:
2494 return createCXString("ObjCClassRef");
2495 case CXCursor_TypeRef:
2496 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002497 case CXCursor_TemplateRef:
2498 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002499 case CXCursor_NamespaceRef:
2500 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002501 case CXCursor_UnexposedExpr:
2502 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002503 case CXCursor_BlockExpr:
2504 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002505 case CXCursor_DeclRefExpr:
2506 return createCXString("DeclRefExpr");
2507 case CXCursor_MemberRefExpr:
2508 return createCXString("MemberRefExpr");
2509 case CXCursor_CallExpr:
2510 return createCXString("CallExpr");
2511 case CXCursor_ObjCMessageExpr:
2512 return createCXString("ObjCMessageExpr");
2513 case CXCursor_UnexposedStmt:
2514 return createCXString("UnexposedStmt");
2515 case CXCursor_InvalidFile:
2516 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002517 case CXCursor_InvalidCode:
2518 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002519 case CXCursor_NoDeclFound:
2520 return createCXString("NoDeclFound");
2521 case CXCursor_NotImplemented:
2522 return createCXString("NotImplemented");
2523 case CXCursor_TranslationUnit:
2524 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002525 case CXCursor_UnexposedAttr:
2526 return createCXString("UnexposedAttr");
2527 case CXCursor_IBActionAttr:
2528 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002529 case CXCursor_IBOutletAttr:
2530 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002531 case CXCursor_IBOutletCollectionAttr:
2532 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002533 case CXCursor_PreprocessingDirective:
2534 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002535 case CXCursor_MacroDefinition:
2536 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002537 case CXCursor_MacroInstantiation:
2538 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002539 case CXCursor_Namespace:
2540 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002541 case CXCursor_LinkageSpec:
2542 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002543 case CXCursor_CXXBaseSpecifier:
2544 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002545 case CXCursor_Constructor:
2546 return createCXString("CXXConstructor");
2547 case CXCursor_Destructor:
2548 return createCXString("CXXDestructor");
2549 case CXCursor_ConversionFunction:
2550 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002551 case CXCursor_TemplateTypeParameter:
2552 return createCXString("TemplateTypeParameter");
2553 case CXCursor_NonTypeTemplateParameter:
2554 return createCXString("NonTypeTemplateParameter");
2555 case CXCursor_TemplateTemplateParameter:
2556 return createCXString("TemplateTemplateParameter");
2557 case CXCursor_FunctionTemplate:
2558 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002559 case CXCursor_ClassTemplate:
2560 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002561 case CXCursor_ClassTemplatePartialSpecialization:
2562 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002563 case CXCursor_NamespaceAlias:
2564 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002565 case CXCursor_UsingDirective:
2566 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002567 case CXCursor_UsingDeclaration:
2568 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002569 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002570
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002571 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002572 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002573}
Steve Naroff89922f82009-08-31 00:59:03 +00002574
Ted Kremeneke68fff62010-02-17 00:41:32 +00002575enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2576 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002577 CXClientData client_data) {
2578 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2579 *BestCursor = cursor;
2580 return CXChildVisit_Recurse;
2581}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002582
Douglas Gregorb9790342010-01-22 21:44:22 +00002583CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2584 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002585 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002586
Douglas Gregorb9790342010-01-22 21:44:22 +00002587 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002588 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2589
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002590 // Translate the given source location to make it point at the beginning of
2591 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002592 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002593
2594 // Guard against an invalid SourceLocation, or we may assert in one
2595 // of the following calls.
2596 if (SLoc.isInvalid())
2597 return clang_getNullCursor();
2598
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002599 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2600 CXXUnit->getASTContext().getLangOptions());
2601
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002602 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2603 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002604 // FIXME: Would be great to have a "hint" cursor, then walk from that
2605 // hint cursor upward until we find a cursor whose source range encloses
2606 // the region of interest, rather than starting from the translation unit.
2607 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002608 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002609 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002610 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002611 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002612 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002613}
2614
Ted Kremenek73885552009-11-17 19:28:59 +00002615CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002616 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002617}
2618
2619unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002620 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002621}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002622
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002623unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002624 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2625}
2626
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002627unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002628 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2629}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002630
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002631unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002632 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2633}
2634
Douglas Gregor97b98722010-01-19 23:20:36 +00002635unsigned clang_isExpression(enum CXCursorKind K) {
2636 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2637}
2638
2639unsigned clang_isStatement(enum CXCursorKind K) {
2640 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2641}
2642
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002643unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2644 return K == CXCursor_TranslationUnit;
2645}
2646
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002647unsigned clang_isPreprocessing(enum CXCursorKind K) {
2648 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2649}
2650
Ted Kremenekad6eff62010-03-08 21:17:29 +00002651unsigned clang_isUnexposed(enum CXCursorKind K) {
2652 switch (K) {
2653 case CXCursor_UnexposedDecl:
2654 case CXCursor_UnexposedExpr:
2655 case CXCursor_UnexposedStmt:
2656 case CXCursor_UnexposedAttr:
2657 return true;
2658 default:
2659 return false;
2660 }
2661}
2662
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002663CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002664 return C.kind;
2665}
2666
Douglas Gregor98258af2010-01-18 22:46:11 +00002667CXSourceLocation clang_getCursorLocation(CXCursor C) {
2668 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002669 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002670 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002671 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2672 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002673 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002674 }
2675
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002676 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002677 std::pair<ObjCProtocolDecl *, SourceLocation> P
2678 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002679 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002680 }
2681
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002682 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002683 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2684 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002685 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002686 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002687
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002688 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002689 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002690 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002691 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002692
2693 case CXCursor_TemplateRef: {
2694 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2695 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2696 }
2697
Douglas Gregor69319002010-08-31 23:48:11 +00002698 case CXCursor_NamespaceRef: {
2699 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2700 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2701 }
2702
Ted Kremenek3064ef92010-08-27 21:34:58 +00002703 case CXCursor_CXXBaseSpecifier: {
2704 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2705 return clang_getNullLocation();
2706 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002707
Douglas Gregorf46034a2010-01-18 23:41:10 +00002708 default:
2709 // FIXME: Need a way to enumerate all non-reference cases.
2710 llvm_unreachable("Missed a reference kind");
2711 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002712 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002713
2714 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002715 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002716 getLocationFromExpr(getCursorExpr(C)));
2717
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002718 if (C.kind == CXCursor_PreprocessingDirective) {
2719 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2720 return cxloc::translateSourceLocation(getCursorContext(C), L);
2721 }
Douglas Gregor48072312010-03-18 15:23:44 +00002722
2723 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002724 SourceLocation L
2725 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002726 return cxloc::translateSourceLocation(getCursorContext(C), L);
2727 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002728
2729 if (C.kind == CXCursor_MacroDefinition) {
2730 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2731 return cxloc::translateSourceLocation(getCursorContext(C), L);
2732 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002733
Ted Kremenek9a700d22010-05-12 06:16:13 +00002734 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002735 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002736
Douglas Gregorf46034a2010-01-18 23:41:10 +00002737 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002738 SourceLocation Loc = D->getLocation();
2739 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2740 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002741 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002742}
Douglas Gregora7bde202010-01-19 00:34:46 +00002743
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002744} // end extern "C"
2745
2746static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002747 if (clang_isReference(C.kind)) {
2748 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002749 case CXCursor_ObjCSuperClassRef:
2750 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002751
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002752 case CXCursor_ObjCProtocolRef:
2753 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002754
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002755 case CXCursor_ObjCClassRef:
2756 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002757
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002758 case CXCursor_TypeRef:
2759 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002760
2761 case CXCursor_TemplateRef:
2762 return getCursorTemplateRef(C).second;
2763
Douglas Gregor69319002010-08-31 23:48:11 +00002764 case CXCursor_NamespaceRef:
2765 return getCursorNamespaceRef(C).second;
2766
Ted Kremenek3064ef92010-08-27 21:34:58 +00002767 case CXCursor_CXXBaseSpecifier:
2768 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2769 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002770
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002771 default:
2772 // FIXME: Need a way to enumerate all non-reference cases.
2773 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002774 }
2775 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002776
2777 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002778 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002779
2780 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002781 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002782
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002783 if (C.kind == CXCursor_PreprocessingDirective)
2784 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002785
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002786 if (C.kind == CXCursor_MacroInstantiation)
2787 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002788
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002789 if (C.kind == CXCursor_MacroDefinition)
2790 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002791
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002792 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2793 return getCursorDecl(C)->getSourceRange();
2794
2795 return SourceRange();
2796}
2797
2798extern "C" {
2799
2800CXSourceRange clang_getCursorExtent(CXCursor C) {
2801 SourceRange R = getRawCursorExtent(C);
2802 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002803 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002804
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002805 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002806}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002807
2808CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002809 if (clang_isInvalid(C.kind))
2810 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002811
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002812 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002813 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002814 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002815
Douglas Gregor97b98722010-01-19 23:20:36 +00002816 if (clang_isExpression(C.kind)) {
2817 Decl *D = getDeclFromExpr(getCursorExpr(C));
2818 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002819 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002820 return clang_getNullCursor();
2821 }
2822
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002823 if (C.kind == CXCursor_MacroInstantiation) {
2824 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2825 return MakeMacroDefinitionCursor(Def, CXXUnit);
2826 }
2827
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002828 if (!clang_isReference(C.kind))
2829 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002830
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002831 switch (C.kind) {
2832 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002833 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002834
2835 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002836 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002837
2838 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002839 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002840
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002841 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002842 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002843
2844 case CXCursor_TemplateRef:
2845 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2846
Douglas Gregor69319002010-08-31 23:48:11 +00002847 case CXCursor_NamespaceRef:
2848 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2849
Ted Kremenek3064ef92010-08-27 21:34:58 +00002850 case CXCursor_CXXBaseSpecifier: {
2851 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2852 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2853 CXXUnit));
2854 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002855
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002856 default:
2857 // We would prefer to enumerate all non-reference cursor kinds here.
2858 llvm_unreachable("Unhandled reference cursor kind");
2859 break;
2860 }
2861 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002862
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002863 return clang_getNullCursor();
2864}
2865
Douglas Gregorb6998662010-01-19 19:34:47 +00002866CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002867 if (clang_isInvalid(C.kind))
2868 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002869
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002870 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002871
Douglas Gregorb6998662010-01-19 19:34:47 +00002872 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002873 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002874 C = clang_getCursorReferenced(C);
2875 WasReference = true;
2876 }
2877
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002878 if (C.kind == CXCursor_MacroInstantiation)
2879 return clang_getCursorReferenced(C);
2880
Douglas Gregorb6998662010-01-19 19:34:47 +00002881 if (!clang_isDeclaration(C.kind))
2882 return clang_getNullCursor();
2883
2884 Decl *D = getCursorDecl(C);
2885 if (!D)
2886 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002887
Douglas Gregorb6998662010-01-19 19:34:47 +00002888 switch (D->getKind()) {
2889 // Declaration kinds that don't really separate the notions of
2890 // declaration and definition.
2891 case Decl::Namespace:
2892 case Decl::Typedef:
2893 case Decl::TemplateTypeParm:
2894 case Decl::EnumConstant:
2895 case Decl::Field:
2896 case Decl::ObjCIvar:
2897 case Decl::ObjCAtDefsField:
2898 case Decl::ImplicitParam:
2899 case Decl::ParmVar:
2900 case Decl::NonTypeTemplateParm:
2901 case Decl::TemplateTemplateParm:
2902 case Decl::ObjCCategoryImpl:
2903 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002904 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002905 case Decl::LinkageSpec:
2906 case Decl::ObjCPropertyImpl:
2907 case Decl::FileScopeAsm:
2908 case Decl::StaticAssert:
2909 case Decl::Block:
2910 return C;
2911
2912 // Declaration kinds that don't make any sense here, but are
2913 // nonetheless harmless.
2914 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002915 break;
2916
2917 // Declaration kinds for which the definition is not resolvable.
2918 case Decl::UnresolvedUsingTypename:
2919 case Decl::UnresolvedUsingValue:
2920 break;
2921
2922 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002923 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2924 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002925
2926 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002927 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002928
2929 case Decl::Enum:
2930 case Decl::Record:
2931 case Decl::CXXRecord:
2932 case Decl::ClassTemplateSpecialization:
2933 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002934 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002935 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002936 return clang_getNullCursor();
2937
2938 case Decl::Function:
2939 case Decl::CXXMethod:
2940 case Decl::CXXConstructor:
2941 case Decl::CXXDestructor:
2942 case Decl::CXXConversion: {
2943 const FunctionDecl *Def = 0;
2944 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002945 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002946 return clang_getNullCursor();
2947 }
2948
2949 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002950 // Ask the variable if it has a definition.
2951 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2952 return MakeCXCursor(Def, CXXUnit);
2953 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002954 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002955
Douglas Gregorb6998662010-01-19 19:34:47 +00002956 case Decl::FunctionTemplate: {
2957 const FunctionDecl *Def = 0;
2958 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002959 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002960 return clang_getNullCursor();
2961 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002962
Douglas Gregorb6998662010-01-19 19:34:47 +00002963 case Decl::ClassTemplate: {
2964 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002965 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002966 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002967 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002968 return clang_getNullCursor();
2969 }
2970
2971 case Decl::Using: {
2972 UsingDecl *Using = cast<UsingDecl>(D);
2973 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002974 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2975 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002976 S != SEnd; ++S) {
2977 if (Def != clang_getNullCursor()) {
2978 // FIXME: We have no way to return multiple results.
2979 return clang_getNullCursor();
2980 }
2981
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002982 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002983 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002984 }
2985
2986 return Def;
2987 }
2988
2989 case Decl::UsingShadow:
2990 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002991 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002992 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002993
2994 case Decl::ObjCMethod: {
2995 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2996 if (Method->isThisDeclarationADefinition())
2997 return C;
2998
2999 // Dig out the method definition in the associated
3000 // @implementation, if we have it.
3001 // FIXME: The ASTs should make finding the definition easier.
3002 if (ObjCInterfaceDecl *Class
3003 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3004 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3005 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3006 Method->isInstanceMethod()))
3007 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003008 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003009
3010 return clang_getNullCursor();
3011 }
3012
3013 case Decl::ObjCCategory:
3014 if (ObjCCategoryImplDecl *Impl
3015 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003016 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003017 return clang_getNullCursor();
3018
3019 case Decl::ObjCProtocol:
3020 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3021 return C;
3022 return clang_getNullCursor();
3023
3024 case Decl::ObjCInterface:
3025 // There are two notions of a "definition" for an Objective-C
3026 // class: the interface and its implementation. When we resolved a
3027 // reference to an Objective-C class, produce the @interface as
3028 // the definition; when we were provided with the interface,
3029 // produce the @implementation as the definition.
3030 if (WasReference) {
3031 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3032 return C;
3033 } else if (ObjCImplementationDecl *Impl
3034 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003035 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003036 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003037
Douglas Gregorb6998662010-01-19 19:34:47 +00003038 case Decl::ObjCProperty:
3039 // FIXME: We don't really know where to find the
3040 // ObjCPropertyImplDecls that implement this property.
3041 return clang_getNullCursor();
3042
3043 case Decl::ObjCCompatibleAlias:
3044 if (ObjCInterfaceDecl *Class
3045 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3046 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003047 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003048
Douglas Gregorb6998662010-01-19 19:34:47 +00003049 return clang_getNullCursor();
3050
3051 case Decl::ObjCForwardProtocol: {
3052 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
3053 if (Forward->protocol_size() == 1)
3054 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003055 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003056 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003057
3058 // FIXME: Cannot return multiple definitions.
3059 return clang_getNullCursor();
3060 }
3061
3062 case Decl::ObjCClass: {
3063 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
3064 if (Class->size() == 1) {
3065 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
3066 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003067 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003068 return clang_getNullCursor();
3069 }
3070
3071 // FIXME: Cannot return multiple definitions.
3072 return clang_getNullCursor();
3073 }
3074
3075 case Decl::Friend:
3076 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003077 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003078 return clang_getNullCursor();
3079
3080 case Decl::FriendTemplate:
3081 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003082 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003083 return clang_getNullCursor();
3084 }
3085
3086 return clang_getNullCursor();
3087}
3088
3089unsigned clang_isCursorDefinition(CXCursor C) {
3090 if (!clang_isDeclaration(C.kind))
3091 return 0;
3092
3093 return clang_getCursorDefinition(C) == C;
3094}
3095
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003096void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003097 const char **startBuf,
3098 const char **endBuf,
3099 unsigned *startLine,
3100 unsigned *startColumn,
3101 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003102 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003103 assert(getCursorDecl(C) && "CXCursor has null decl");
3104 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003105 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3106 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003107
Steve Naroff4ade6d62009-09-23 17:52:52 +00003108 SourceManager &SM = FD->getASTContext().getSourceManager();
3109 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3110 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3111 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3112 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3113 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3114 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3115}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003116
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003117void clang_enableStackTraces(void) {
3118 llvm::sys::PrintStackTraceOnErrorSignal();
3119}
3120
Ted Kremenekfb480492010-01-13 21:46:36 +00003121} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003122
Ted Kremenekfb480492010-01-13 21:46:36 +00003123//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003124// Token-based Operations.
3125//===----------------------------------------------------------------------===//
3126
3127/* CXToken layout:
3128 * int_data[0]: a CXTokenKind
3129 * int_data[1]: starting token location
3130 * int_data[2]: token length
3131 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003132 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003133 * otherwise unused.
3134 */
3135extern "C" {
3136
3137CXTokenKind clang_getTokenKind(CXToken CXTok) {
3138 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3139}
3140
3141CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3142 switch (clang_getTokenKind(CXTok)) {
3143 case CXToken_Identifier:
3144 case CXToken_Keyword:
3145 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003146 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3147 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003148
3149 case CXToken_Literal: {
3150 // We have stashed the starting pointer in the ptr_data field. Use it.
3151 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003152 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003153 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003154
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003155 case CXToken_Punctuation:
3156 case CXToken_Comment:
3157 break;
3158 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003159
3160 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003161 // deconstructing the source location.
3162 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3163 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003164 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003165
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003166 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3167 std::pair<FileID, unsigned> LocInfo
3168 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003169 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003170 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003171 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3172 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003173 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003174
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003175 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003176}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003177
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003178CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3179 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3180 if (!CXXUnit)
3181 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003182
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003183 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3184 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3185}
3186
3187CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3188 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003189 if (!CXXUnit)
3190 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003191
3192 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003193 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3194}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003195
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003196void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3197 CXToken **Tokens, unsigned *NumTokens) {
3198 if (Tokens)
3199 *Tokens = 0;
3200 if (NumTokens)
3201 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003202
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003203 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3204 if (!CXXUnit || !Tokens || !NumTokens)
3205 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003206
Douglas Gregorbdf60622010-03-05 21:16:25 +00003207 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3208
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003209 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003210 if (R.isInvalid())
3211 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003212
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003213 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3214 std::pair<FileID, unsigned> BeginLocInfo
3215 = SourceMgr.getDecomposedLoc(R.getBegin());
3216 std::pair<FileID, unsigned> EndLocInfo
3217 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003218
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003219 // Cannot tokenize across files.
3220 if (BeginLocInfo.first != EndLocInfo.first)
3221 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003222
3223 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003224 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003225 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003226 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003227 if (Invalid)
3228 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003229
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003230 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3231 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003232 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003233 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003234
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003235 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003236 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003237 llvm::SmallVector<CXToken, 32> CXTokens;
3238 Token Tok;
3239 do {
3240 // Lex the next token
3241 Lex.LexFromRawLexer(Tok);
3242 if (Tok.is(tok::eof))
3243 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003244
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003245 // Initialize the CXToken.
3246 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003247
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003248 // - Common fields
3249 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3250 CXTok.int_data[2] = Tok.getLength();
3251 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003252
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003253 // - Kind-specific fields
3254 if (Tok.isLiteral()) {
3255 CXTok.int_data[0] = CXToken_Literal;
3256 CXTok.ptr_data = (void *)Tok.getLiteralData();
3257 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003258 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003259 std::pair<FileID, unsigned> LocInfo
3260 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003261 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003262 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003263 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3264 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003265 return;
3266
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003267 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003268 IdentifierInfo *II
3269 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003270
3271 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3272 CXTok.int_data[0] = CXToken_Keyword;
3273 }
3274 else {
3275 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3276 CXToken_Identifier
3277 : CXToken_Keyword;
3278 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003279 CXTok.ptr_data = II;
3280 } else if (Tok.is(tok::comment)) {
3281 CXTok.int_data[0] = CXToken_Comment;
3282 CXTok.ptr_data = 0;
3283 } else {
3284 CXTok.int_data[0] = CXToken_Punctuation;
3285 CXTok.ptr_data = 0;
3286 }
3287 CXTokens.push_back(CXTok);
3288 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003289
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003290 if (CXTokens.empty())
3291 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003292
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003293 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3294 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3295 *NumTokens = CXTokens.size();
3296}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003297
Ted Kremenek6db61092010-05-05 00:55:15 +00003298void clang_disposeTokens(CXTranslationUnit TU,
3299 CXToken *Tokens, unsigned NumTokens) {
3300 free(Tokens);
3301}
3302
3303} // end: extern "C"
3304
3305//===----------------------------------------------------------------------===//
3306// Token annotation APIs.
3307//===----------------------------------------------------------------------===//
3308
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003309typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003310static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3311 CXCursor parent,
3312 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003313namespace {
3314class AnnotateTokensWorker {
3315 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003316 CXToken *Tokens;
3317 CXCursor *Cursors;
3318 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003319 unsigned TokIdx;
3320 CursorVisitor AnnotateVis;
3321 SourceManager &SrcMgr;
3322
3323 bool MoreTokens() const { return TokIdx < NumTokens; }
3324 unsigned NextToken() const { return TokIdx; }
3325 void AdvanceToken() { ++TokIdx; }
3326 SourceLocation GetTokenLoc(unsigned tokI) {
3327 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3328 }
3329
Ted Kremenek6db61092010-05-05 00:55:15 +00003330public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003331 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003332 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3333 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003334 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003335 NumTokens(numTokens), TokIdx(0),
3336 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3337 Decl::MaxPCHLevel, RegionOfInterest),
3338 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003339
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003340 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003341 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003342 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003343};
3344}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003345
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003346void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3347 // Walk the AST within the region of interest, annotating tokens
3348 // along the way.
3349 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003350
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003351 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3352 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3353 if (Pos != Annotated.end())
3354 Cursors[I] = Pos->second;
3355 }
3356
3357 // Finish up annotating any tokens left.
3358 if (!MoreTokens())
3359 return;
3360
3361 const CXCursor &C = clang_getNullCursor();
3362 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3363 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3364 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003365 }
3366}
3367
Ted Kremenek6db61092010-05-05 00:55:15 +00003368enum CXChildVisitResult
3369AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003370 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3371 // We can always annotate a preprocessing directive/macro instantiation.
3372 if (clang_isPreprocessing(cursor.kind)) {
3373 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003374 return CXChildVisit_Recurse;
3375 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003376
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003377 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003378
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003379 if (cursorRange.isInvalid())
3380 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003381
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003382 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3383
Ted Kremeneka333c662010-05-12 05:29:33 +00003384 // Adjust the annotated range based specific declarations.
3385 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3386 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003387 Decl *D = cxcursor::getCursorDecl(cursor);
3388 // Don't visit synthesized ObjC methods, since they have no syntatic
3389 // representation in the source.
3390 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3391 if (MD->isSynthesized())
3392 return CXChildVisit_Continue;
3393 }
3394 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003395 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3396 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003397 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003398 if (TLoc.isValid() &&
3399 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003400 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003401 }
3402 }
3403 }
3404
Ted Kremenek3f404602010-08-14 01:14:06 +00003405 // If the location of the cursor occurs within a macro instantiation, record
3406 // the spelling location of the cursor in our annotation map. We can then
3407 // paper over the token labelings during a post-processing step to try and
3408 // get cursor mappings for tokens that are the *arguments* of a macro
3409 // instantiation.
3410 if (L.isMacroID()) {
3411 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3412 // Only invalidate the old annotation if it isn't part of a preprocessing
3413 // directive. Here we assume that the default construction of CXCursor
3414 // results in CXCursor.kind being an initialized value (i.e., 0). If
3415 // this isn't the case, we can fix by doing lookup + insertion.
3416
3417 CXCursor &oldC = Annotated[rawEncoding];
3418 if (!clang_isPreprocessing(oldC.kind))
3419 oldC = cursor;
3420 }
3421
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003422 const enum CXCursorKind K = clang_getCursorKind(parent);
3423 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003424 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3425 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003426
3427 while (MoreTokens()) {
3428 const unsigned I = NextToken();
3429 SourceLocation TokLoc = GetTokenLoc(I);
3430 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3431 case RangeBefore:
3432 Cursors[I] = updateC;
3433 AdvanceToken();
3434 continue;
3435 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003436 case RangeOverlap:
3437 break;
3438 }
3439 break;
3440 }
3441
3442 // Visit children to get their cursor information.
3443 const unsigned BeforeChildren = NextToken();
3444 VisitChildren(cursor);
3445 const unsigned AfterChildren = NextToken();
3446
3447 // Adjust 'Last' to the last token within the extent of the cursor.
3448 while (MoreTokens()) {
3449 const unsigned I = NextToken();
3450 SourceLocation TokLoc = GetTokenLoc(I);
3451 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3452 case RangeBefore:
3453 assert(0 && "Infeasible");
3454 case RangeAfter:
3455 break;
3456 case RangeOverlap:
3457 Cursors[I] = updateC;
3458 AdvanceToken();
3459 continue;
3460 }
3461 break;
3462 }
3463 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003464
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003465 // Scan the tokens that are at the beginning of the cursor, but are not
3466 // capture by the child cursors.
3467
3468 // For AST elements within macros, rely on a post-annotate pass to
3469 // to correctly annotate the tokens with cursors. Otherwise we can
3470 // get confusing results of having tokens that map to cursors that really
3471 // are expanded by an instantiation.
3472 if (L.isMacroID())
3473 cursor = clang_getNullCursor();
3474
3475 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3476 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3477 break;
3478 Cursors[I] = cursor;
3479 }
3480 // Scan the tokens that are at the end of the cursor, but are not captured
3481 // but the child cursors.
3482 for (unsigned I = AfterChildren; I != Last; ++I)
3483 Cursors[I] = cursor;
3484
3485 TokIdx = Last;
3486 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003487}
3488
Ted Kremenek6db61092010-05-05 00:55:15 +00003489static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3490 CXCursor parent,
3491 CXClientData client_data) {
3492 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3493}
3494
3495extern "C" {
3496
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003497void clang_annotateTokens(CXTranslationUnit TU,
3498 CXToken *Tokens, unsigned NumTokens,
3499 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003500
3501 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003502 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003503
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003504 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003505 if (!CXXUnit) {
3506 // Any token we don't specifically annotate will have a NULL cursor.
3507 const CXCursor &C = clang_getNullCursor();
3508 for (unsigned I = 0; I != NumTokens; ++I)
3509 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003510 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003511 }
3512
Douglas Gregorbdf60622010-03-05 21:16:25 +00003513 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003514
Douglas Gregor0396f462010-03-19 05:22:59 +00003515 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003516 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003517 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3518 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003519 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3520 clang_getTokenLocation(TU,
3521 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003522
Douglas Gregor0396f462010-03-19 05:22:59 +00003523 // A mapping from the source locations found when re-lexing or traversing the
3524 // region of interest to the corresponding cursors.
3525 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003526
3527 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003528 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003529 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3530 std::pair<FileID, unsigned> BeginLocInfo
3531 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3532 std::pair<FileID, unsigned> EndLocInfo
3533 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003534
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003535 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003536 bool Invalid = false;
3537 if (BeginLocInfo.first == EndLocInfo.first &&
3538 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3539 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003540 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3541 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003542 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003543 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003544 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003545
3546 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003547 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003548 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003549 Token Tok;
3550 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003551
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003552 reprocess:
3553 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3554 // We have found a preprocessing directive. Gobble it up so that we
3555 // don't see it while preprocessing these tokens later, but keep track of
3556 // all of the token locations inside this preprocessing directive so that
3557 // we can annotate them appropriately.
3558 //
3559 // FIXME: Some simple tests here could identify macro definitions and
3560 // #undefs, to provide specific cursor kinds for those.
3561 std::vector<SourceLocation> Locations;
3562 do {
3563 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003564 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003565 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003566
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003567 using namespace cxcursor;
3568 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003569 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3570 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003571 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003572 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3573 Annotated[Locations[I].getRawEncoding()] = Cursor;
3574 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003575
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003576 if (Tok.isAtStartOfLine())
3577 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003578
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003579 continue;
3580 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003581
Douglas Gregor48072312010-03-18 15:23:44 +00003582 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003583 break;
3584 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003585 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003586
Douglas Gregor0396f462010-03-19 05:22:59 +00003587 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003588 // a specific cursor.
3589 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3590 CXXUnit, RegionOfInterest);
3591 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003592}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003593} // end: extern "C"
3594
3595//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003596// Operations for querying linkage of a cursor.
3597//===----------------------------------------------------------------------===//
3598
3599extern "C" {
3600CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003601 if (!clang_isDeclaration(cursor.kind))
3602 return CXLinkage_Invalid;
3603
Ted Kremenek16b42592010-03-03 06:36:57 +00003604 Decl *D = cxcursor::getCursorDecl(cursor);
3605 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3606 switch (ND->getLinkage()) {
3607 case NoLinkage: return CXLinkage_NoLinkage;
3608 case InternalLinkage: return CXLinkage_Internal;
3609 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3610 case ExternalLinkage: return CXLinkage_External;
3611 };
3612
3613 return CXLinkage_Invalid;
3614}
3615} // end: extern "C"
3616
3617//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003618// Operations for querying language of a cursor.
3619//===----------------------------------------------------------------------===//
3620
3621static CXLanguageKind getDeclLanguage(const Decl *D) {
3622 switch (D->getKind()) {
3623 default:
3624 break;
3625 case Decl::ImplicitParam:
3626 case Decl::ObjCAtDefsField:
3627 case Decl::ObjCCategory:
3628 case Decl::ObjCCategoryImpl:
3629 case Decl::ObjCClass:
3630 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003631 case Decl::ObjCForwardProtocol:
3632 case Decl::ObjCImplementation:
3633 case Decl::ObjCInterface:
3634 case Decl::ObjCIvar:
3635 case Decl::ObjCMethod:
3636 case Decl::ObjCProperty:
3637 case Decl::ObjCPropertyImpl:
3638 case Decl::ObjCProtocol:
3639 return CXLanguage_ObjC;
3640 case Decl::CXXConstructor:
3641 case Decl::CXXConversion:
3642 case Decl::CXXDestructor:
3643 case Decl::CXXMethod:
3644 case Decl::CXXRecord:
3645 case Decl::ClassTemplate:
3646 case Decl::ClassTemplatePartialSpecialization:
3647 case Decl::ClassTemplateSpecialization:
3648 case Decl::Friend:
3649 case Decl::FriendTemplate:
3650 case Decl::FunctionTemplate:
3651 case Decl::LinkageSpec:
3652 case Decl::Namespace:
3653 case Decl::NamespaceAlias:
3654 case Decl::NonTypeTemplateParm:
3655 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003656 case Decl::TemplateTemplateParm:
3657 case Decl::TemplateTypeParm:
3658 case Decl::UnresolvedUsingTypename:
3659 case Decl::UnresolvedUsingValue:
3660 case Decl::Using:
3661 case Decl::UsingDirective:
3662 case Decl::UsingShadow:
3663 return CXLanguage_CPlusPlus;
3664 }
3665
3666 return CXLanguage_C;
3667}
3668
3669extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003670
3671enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3672 if (clang_isDeclaration(cursor.kind))
3673 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3674 if (D->hasAttr<UnavailableAttr>() ||
3675 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3676 return CXAvailability_Available;
3677
3678 if (D->hasAttr<DeprecatedAttr>())
3679 return CXAvailability_Deprecated;
3680 }
3681
3682 return CXAvailability_Available;
3683}
3684
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003685CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3686 if (clang_isDeclaration(cursor.kind))
3687 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3688
3689 return CXLanguage_Invalid;
3690}
3691} // end: extern "C"
3692
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003693
3694//===----------------------------------------------------------------------===//
3695// C++ AST instrospection.
3696//===----------------------------------------------------------------------===//
3697
3698extern "C" {
3699unsigned clang_CXXMethod_isStatic(CXCursor C) {
3700 if (!clang_isDeclaration(C.kind))
3701 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003702
3703 CXXMethodDecl *Method = 0;
3704 Decl *D = cxcursor::getCursorDecl(C);
3705 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3706 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3707 else
3708 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3709 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003710}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003711
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003712} // end: extern "C"
3713
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003714//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003715// Attribute introspection.
3716//===----------------------------------------------------------------------===//
3717
3718extern "C" {
3719CXType clang_getIBOutletCollectionType(CXCursor C) {
3720 if (C.kind != CXCursor_IBOutletCollectionAttr)
3721 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3722
3723 IBOutletCollectionAttr *A =
3724 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3725
3726 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3727}
3728} // end: extern "C"
3729
3730//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003731// CXString Operations.
3732//===----------------------------------------------------------------------===//
3733
3734extern "C" {
3735const char *clang_getCString(CXString string) {
3736 return string.Spelling;
3737}
3738
3739void clang_disposeString(CXString string) {
3740 if (string.MustFreeString && string.Spelling)
3741 free((void*)string.Spelling);
3742}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003743
Ted Kremenekfb480492010-01-13 21:46:36 +00003744} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003745
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003746namespace clang { namespace cxstring {
3747CXString createCXString(const char *String, bool DupString){
3748 CXString Str;
3749 if (DupString) {
3750 Str.Spelling = strdup(String);
3751 Str.MustFreeString = 1;
3752 } else {
3753 Str.Spelling = String;
3754 Str.MustFreeString = 0;
3755 }
3756 return Str;
3757}
3758
3759CXString createCXString(llvm::StringRef String, bool DupString) {
3760 CXString Result;
3761 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3762 char *Spelling = (char *)malloc(String.size() + 1);
3763 memmove(Spelling, String.data(), String.size());
3764 Spelling[String.size()] = 0;
3765 Result.Spelling = Spelling;
3766 Result.MustFreeString = 1;
3767 } else {
3768 Result.Spelling = String.data();
3769 Result.MustFreeString = 0;
3770 }
3771 return Result;
3772}
3773}}
3774
Ted Kremenek04bb7162010-01-22 22:44:15 +00003775//===----------------------------------------------------------------------===//
3776// Misc. utility functions.
3777//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003778
Ted Kremenek04bb7162010-01-22 22:44:15 +00003779extern "C" {
3780
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003781CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003782 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003783}
3784
3785} // end: extern "C"