blob: d3c3c6e4face47e1bb6a347d0c223f2cb6453770 [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 Gregor6f7198f2010-09-02 22:09:03 +0000389 // FIXME: CXXTemporaryObjectExpr has poor source-location information
390 // FIXME: CXXScalarValueInitExpr has poor source-location information
391 // FIXME: CXXNewExpr has poor source-location information
392 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000393};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000394
Ted Kremenekab188932010-01-05 19:32:54 +0000395} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000396
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000397static SourceRange getRawCursorExtent(CXCursor C);
398
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000399RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000400 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
401}
402
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403/// \brief Visit the given cursor and, if requested by the visitor,
404/// its children.
405///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000406/// \param Cursor the cursor to visit.
407///
408/// \param CheckRegionOfInterest if true, then the caller already checked that
409/// this cursor is within the region of interest.
410///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000411/// \returns true if the visitation should be aborted, false if it
412/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000413bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000414 if (clang_isInvalid(Cursor.kind))
415 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000416
Douglas Gregorb1373d02010-01-20 20:59:29 +0000417 if (clang_isDeclaration(Cursor.kind)) {
418 Decl *D = getCursorDecl(Cursor);
419 assert(D && "Invalid declaration cursor");
420 if (D->getPCHLevel() > MaxPCHLevel)
421 return false;
422
423 if (D->isImplicit())
424 return false;
425 }
426
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000427 // If we have a range of interest, and this cursor doesn't intersect with it,
428 // we're done.
429 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000430 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000431 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000432 return false;
433 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000434
Douglas Gregorb1373d02010-01-20 20:59:29 +0000435 switch (Visitor(Cursor, Parent, ClientData)) {
436 case CXChildVisit_Break:
437 return true;
438
439 case CXChildVisit_Continue:
440 return false;
441
442 case CXChildVisit_Recurse:
443 return VisitChildren(Cursor);
444 }
445
Douglas Gregorfd643772010-01-25 16:45:46 +0000446 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000447}
448
Douglas Gregor788f5a12010-03-20 00:41:21 +0000449std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
450CursorVisitor::getPreprocessedEntities() {
451 PreprocessingRecord &PPRec
452 = *TU->getPreprocessor().getPreprocessingRecord();
453
454 bool OnlyLocalDecls
455 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
456
457 // There is no region of interest; we have to walk everything.
458 if (RegionOfInterest.isInvalid())
459 return std::make_pair(PPRec.begin(OnlyLocalDecls),
460 PPRec.end(OnlyLocalDecls));
461
462 // Find the file in which the region of interest lands.
463 SourceManager &SM = TU->getSourceManager();
464 std::pair<FileID, unsigned> Begin
465 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
466 std::pair<FileID, unsigned> End
467 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
468
469 // The region of interest spans files; we have to walk everything.
470 if (Begin.first != End.first)
471 return std::make_pair(PPRec.begin(OnlyLocalDecls),
472 PPRec.end(OnlyLocalDecls));
473
474 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
475 = TU->getPreprocessedEntitiesByFile();
476 if (ByFileMap.empty()) {
477 // Build the mapping from files to sets of preprocessed entities.
478 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
479 EEnd = PPRec.end(OnlyLocalDecls);
480 E != EEnd; ++E) {
481 std::pair<FileID, unsigned> P
482 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
483 ByFileMap[P.first].push_back(*E);
484 }
485 }
486
487 return std::make_pair(ByFileMap[Begin.first].begin(),
488 ByFileMap[Begin.first].end());
489}
490
Douglas Gregorb1373d02010-01-20 20:59:29 +0000491/// \brief Visit the children of the given cursor.
492///
493/// \returns true if the visitation should be aborted, false if it
494/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000495bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000496 if (clang_isReference(Cursor.kind)) {
497 // By definition, references have no children.
498 return false;
499 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000500
501 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000502 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000503 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000504
Douglas Gregorb1373d02010-01-20 20:59:29 +0000505 if (clang_isDeclaration(Cursor.kind)) {
506 Decl *D = getCursorDecl(Cursor);
507 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000508 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000509 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000510
Douglas Gregora59e3902010-01-21 23:27:09 +0000511 if (clang_isStatement(Cursor.kind))
512 return Visit(getCursorStmt(Cursor));
513 if (clang_isExpression(Cursor.kind))
514 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000515
Douglas Gregorb1373d02010-01-20 20:59:29 +0000516 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000517 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000518 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
519 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000520 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
521 TLEnd = CXXUnit->top_level_end();
522 TL != TLEnd; ++TL) {
523 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000524 return true;
525 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000526 } else if (VisitDeclContext(
527 CXXUnit->getASTContext().getTranslationUnitDecl()))
528 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000529
Douglas Gregor0396f462010-03-19 05:22:59 +0000530 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000531 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000532 // FIXME: Once we have the ability to deserialize a preprocessing record,
533 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000534 PreprocessingRecord::iterator E, EEnd;
535 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000536 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
537 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
538 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000539
Douglas Gregor0396f462010-03-19 05:22:59 +0000540 continue;
541 }
542
543 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
544 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
545 return true;
546
547 continue;
548 }
549 }
550 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000551 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000552 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000553
Douglas Gregorb1373d02010-01-20 20:59:29 +0000554 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000555 return false;
556}
557
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000558bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000559 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
560 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000561
Ted Kremenek664cffd2010-07-22 11:30:19 +0000562 if (Stmt *Body = B->getBody())
563 return Visit(MakeCXCursor(Body, StmtParent, TU));
564
565 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000566}
567
Douglas Gregorb1373d02010-01-20 20:59:29 +0000568bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000569 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000570 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000571
Ted Kremenek23173d72010-05-18 21:09:07 +0000572 Decl *D = *I;
573 if (D->getLexicalDeclContext() != DC)
574 continue;
575
576 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000577
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000578 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000579 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000580 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000581 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000582
583 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000584 case RangeBefore:
585 // This declaration comes before the region of interest; skip it.
586 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000587
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000588 case RangeAfter:
589 // This declaration comes after the region of interest; we're done.
590 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000591
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000592 case RangeOverlap:
593 // This declaration overlaps the region of interest; visit it.
594 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000595 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000596 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000597
Daniel Dunbard52864b2010-02-14 10:02:57 +0000598 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000599 return true;
600 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000601
Douglas Gregorb1373d02010-01-20 20:59:29 +0000602 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000603}
604
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000605bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
606 llvm_unreachable("Translation units are visited directly by Visit()");
607 return false;
608}
609
610bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
611 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
612 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000613
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000614 return false;
615}
616
617bool CursorVisitor::VisitTagDecl(TagDecl *D) {
618 return VisitDeclContext(D);
619}
620
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000621bool CursorVisitor::VisitClassTemplateSpecializationDecl(
622 ClassTemplateSpecializationDecl *D) {
623 bool ShouldVisitBody = false;
624 switch (D->getSpecializationKind()) {
625 case TSK_Undeclared:
626 case TSK_ImplicitInstantiation:
627 // Nothing to visit
628 return false;
629
630 case TSK_ExplicitInstantiationDeclaration:
631 case TSK_ExplicitInstantiationDefinition:
632 break;
633
634 case TSK_ExplicitSpecialization:
635 ShouldVisitBody = true;
636 break;
637 }
638
639 // Visit the template arguments used in the specialization.
640 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
641 TypeLoc TL = SpecType->getTypeLoc();
642 if (TemplateSpecializationTypeLoc *TSTLoc
643 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
644 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
645 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
646 return true;
647 }
648 }
649
650 if (ShouldVisitBody && VisitCXXRecordDecl(D))
651 return true;
652
653 return false;
654}
655
Douglas Gregor74dbe642010-08-31 19:31:58 +0000656bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
657 ClassTemplatePartialSpecializationDecl *D) {
658 // FIXME: Visit the "outer" template parameter lists on the TagDecl
659 // before visiting these template parameters.
660 if (VisitTemplateParameters(D->getTemplateParameters()))
661 return true;
662
663 // Visit the partial specialization arguments.
664 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
665 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
666 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
667 return true;
668
669 return VisitCXXRecordDecl(D);
670}
671
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000672bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000673 // Visit the default argument.
674 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
675 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
676 if (Visit(DefArg->getTypeLoc()))
677 return true;
678
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000679 return false;
680}
681
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000682bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
683 if (Expr *Init = D->getInitExpr())
684 return Visit(MakeCXCursor(Init, StmtParent, TU));
685 return false;
686}
687
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000688bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
689 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
690 if (Visit(TSInfo->getTypeLoc()))
691 return true;
692
693 return false;
694}
695
Douglas Gregorb1373d02010-01-20 20:59:29 +0000696bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000697 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
698 // Visit the function declaration's syntactic components in the order
699 // written. This requires a bit of work.
700 TypeLoc TL = TSInfo->getTypeLoc();
701 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
702
703 // If we have a function declared directly (without the use of a typedef),
704 // visit just the return type. Otherwise, just visit the function's type
705 // now.
706 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
707 (!FTL && Visit(TL)))
708 return true;
709
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000710 // Visit the nested-name-specifier, if present.
711 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
712 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
713 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000714
715 // Visit the declaration name.
716 if (VisitDeclarationNameInfo(ND->getNameInfo()))
717 return true;
718
719 // FIXME: Visit explicitly-specified template arguments!
720
721 // Visit the function parameters, if we have a function type.
722 if (FTL && VisitFunctionTypeLoc(*FTL, true))
723 return true;
724
725 // FIXME: Attributes?
726 }
727
Douglas Gregora59e3902010-01-21 23:27:09 +0000728 if (ND->isThisDeclarationADefinition() &&
729 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
730 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000731
Douglas Gregorb1373d02010-01-20 20:59:29 +0000732 return false;
733}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000734
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000735bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
736 if (VisitDeclaratorDecl(D))
737 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000738
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000739 if (Expr *BitWidth = D->getBitWidth())
740 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000741
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000742 return false;
743}
744
745bool CursorVisitor::VisitVarDecl(VarDecl *D) {
746 if (VisitDeclaratorDecl(D))
747 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000748
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000749 if (Expr *Init = D->getInit())
750 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000751
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000752 return false;
753}
754
Douglas Gregor84b51d72010-09-01 20:16:53 +0000755bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
756 if (VisitDeclaratorDecl(D))
757 return true;
758
759 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
760 if (Expr *DefArg = D->getDefaultArgument())
761 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
762
763 return false;
764}
765
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000766bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
767 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
768 // before visiting these template parameters.
769 if (VisitTemplateParameters(D->getTemplateParameters()))
770 return true;
771
772 return VisitFunctionDecl(D->getTemplatedDecl());
773}
774
Douglas Gregor39d6f072010-08-31 19:02:00 +0000775bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
776 // FIXME: Visit the "outer" template parameter lists on the TagDecl
777 // before visiting these template parameters.
778 if (VisitTemplateParameters(D->getTemplateParameters()))
779 return true;
780
781 return VisitCXXRecordDecl(D->getTemplatedDecl());
782}
783
Douglas Gregor84b51d72010-09-01 20:16:53 +0000784bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
785 if (VisitTemplateParameters(D->getTemplateParameters()))
786 return true;
787
788 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
789 VisitTemplateArgumentLoc(D->getDefaultArgument()))
790 return true;
791
792 return false;
793}
794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000796 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
797 if (Visit(TSInfo->getTypeLoc()))
798 return true;
799
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000800 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000801 PEnd = ND->param_end();
802 P != PEnd; ++P) {
803 if (Visit(MakeCXCursor(*P, TU)))
804 return true;
805 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000806
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000807 if (ND->isThisDeclarationADefinition() &&
808 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
809 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000810
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000811 return false;
812}
813
Douglas Gregora59e3902010-01-21 23:27:09 +0000814bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
815 return VisitDeclContext(D);
816}
817
Douglas Gregorb1373d02010-01-20 20:59:29 +0000818bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000819 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
820 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000821 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000822
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000823 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
824 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
825 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000826 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000827 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000828
Douglas Gregora59e3902010-01-21 23:27:09 +0000829 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000830}
831
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000832bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
833 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
834 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
835 E = PID->protocol_end(); I != E; ++I, ++PL)
836 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
837 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000838
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000839 return VisitObjCContainerDecl(PID);
840}
841
Ted Kremenek23173d72010-05-18 21:09:07 +0000842bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000843 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
844 return true;
845
Ted Kremenek23173d72010-05-18 21:09:07 +0000846 // FIXME: This implements a workaround with @property declarations also being
847 // installed in the DeclContext for the @interface. Eventually this code
848 // should be removed.
849 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
850 if (!CDecl || !CDecl->IsClassExtension())
851 return false;
852
853 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
854 if (!ID)
855 return false;
856
857 IdentifierInfo *PropertyId = PD->getIdentifier();
858 ObjCPropertyDecl *prevDecl =
859 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
860
861 if (!prevDecl)
862 return false;
863
864 // Visit synthesized methods since they will be skipped when visiting
865 // the @interface.
866 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
867 if (MD->isSynthesized())
868 if (Visit(MakeCXCursor(MD, TU)))
869 return true;
870
871 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
872 if (MD->isSynthesized())
873 if (Visit(MakeCXCursor(MD, TU)))
874 return true;
875
876 return false;
877}
878
Douglas Gregorb1373d02010-01-20 20:59:29 +0000879bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000880 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000881 if (D->getSuperClass() &&
882 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000883 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000884 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000885 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000886
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000887 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
888 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
889 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000890 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000891 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000892
Douglas Gregora59e3902010-01-21 23:27:09 +0000893 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000894}
895
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000896bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
897 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000898}
899
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000900bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000901 // 'ID' could be null when dealing with invalid code.
902 if (ObjCInterfaceDecl *ID = D->getClassInterface())
903 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
904 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000905
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000906 return VisitObjCImplDecl(D);
907}
908
909bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
910#if 0
911 // Issue callbacks for super class.
912 // FIXME: No source location information!
913 if (D->getSuperClass() &&
914 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000915 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000916 TU)))
917 return true;
918#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000919
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000920 return VisitObjCImplDecl(D);
921}
922
923bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
924 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
925 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
926 E = D->protocol_end();
927 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000928 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000929 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000930
931 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000932}
933
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000934bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
935 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
936 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
937 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000938
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000939 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000940}
941
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000942bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
943 return VisitDeclContext(D);
944}
945
Douglas Gregor69319002010-08-31 23:48:11 +0000946bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000947 // Visit nested-name-specifier.
948 if (NestedNameSpecifier *Qualifier = D->getQualifier())
949 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
950 return true;
Douglas Gregor69319002010-08-31 23:48:11 +0000951
952 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
953 D->getTargetNameLoc(), TU));
954}
955
Douglas Gregor7e242562010-09-01 19:52:22 +0000956bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000957 // Visit nested-name-specifier.
958 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
959 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
960 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +0000961
962 // FIXME: Provide a multi-reference of some kind for all of the declarations
963 // that the using declaration refers to. We don't have this kind of cursor
964 // yet.
965
966 return VisitDeclarationNameInfo(D->getNameInfo());
967}
968
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000969bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000970 // Visit nested-name-specifier.
971 if (NestedNameSpecifier *Qualifier = D->getQualifier())
972 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
973 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000974
975 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
976 D->getIdentLocation(), TU));
977}
978
Douglas Gregor7e242562010-09-01 19:52:22 +0000979bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000980 // Visit nested-name-specifier.
981 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
982 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
983 return true;
984
Douglas Gregor7e242562010-09-01 19:52:22 +0000985 return VisitDeclarationNameInfo(D->getNameInfo());
986}
987
988bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
989 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000990 // Visit nested-name-specifier.
991 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
992 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
993 return true;
994
Douglas Gregor7e242562010-09-01 19:52:22 +0000995 return false;
996}
997
Douglas Gregor01829d32010-08-31 14:41:23 +0000998bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
999 switch (Name.getName().getNameKind()) {
1000 case clang::DeclarationName::Identifier:
1001 case clang::DeclarationName::CXXLiteralOperatorName:
1002 case clang::DeclarationName::CXXOperatorName:
1003 case clang::DeclarationName::CXXUsingDirective:
1004 return false;
1005
1006 case clang::DeclarationName::CXXConstructorName:
1007 case clang::DeclarationName::CXXDestructorName:
1008 case clang::DeclarationName::CXXConversionFunctionName:
1009 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1010 return Visit(TSInfo->getTypeLoc());
1011 return false;
1012
1013 case clang::DeclarationName::ObjCZeroArgSelector:
1014 case clang::DeclarationName::ObjCOneArgSelector:
1015 case clang::DeclarationName::ObjCMultiArgSelector:
1016 // FIXME: Per-identifier location info?
1017 return false;
1018 }
1019
1020 return false;
1021}
1022
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001023bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1024 SourceRange Range) {
1025 // FIXME: This whole routine is a hack to work around the lack of proper
1026 // source information in nested-name-specifiers (PR5791). Since we do have
1027 // a beginning source location, we can visit the first component of the
1028 // nested-name-specifier, if it's a single-token component.
1029 if (!NNS)
1030 return false;
1031
1032 // Get the first component in the nested-name-specifier.
1033 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1034 NNS = Prefix;
1035
1036 switch (NNS->getKind()) {
1037 case NestedNameSpecifier::Namespace:
1038 // FIXME: The token at this source location might actually have been a
1039 // namespace alias, but we don't model that. Lame!
1040 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1041 TU));
1042
1043 case NestedNameSpecifier::TypeSpec: {
1044 // If the type has a form where we know that the beginning of the source
1045 // range matches up with a reference cursor. Visit the appropriate reference
1046 // cursor.
1047 Type *T = NNS->getAsType();
1048 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1049 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1050 if (const TagType *Tag = dyn_cast<TagType>(T))
1051 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1052 if (const TemplateSpecializationType *TST
1053 = dyn_cast<TemplateSpecializationType>(T))
1054 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1055 break;
1056 }
1057
1058 case NestedNameSpecifier::TypeSpecWithTemplate:
1059 case NestedNameSpecifier::Global:
1060 case NestedNameSpecifier::Identifier:
1061 break;
1062 }
1063
1064 return false;
1065}
1066
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001067bool CursorVisitor::VisitTemplateParameters(
1068 const TemplateParameterList *Params) {
1069 if (!Params)
1070 return false;
1071
1072 for (TemplateParameterList::const_iterator P = Params->begin(),
1073 PEnd = Params->end();
1074 P != PEnd; ++P) {
1075 if (Visit(MakeCXCursor(*P, TU)))
1076 return true;
1077 }
1078
1079 return false;
1080}
1081
Douglas Gregor0b36e612010-08-31 20:37:03 +00001082bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1083 switch (Name.getKind()) {
1084 case TemplateName::Template:
1085 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1086
1087 case TemplateName::OverloadedTemplate:
1088 // FIXME: We need a way to return multiple lookup results in a single
1089 // cursor.
1090 return false;
1091
1092 case TemplateName::DependentTemplate:
1093 // FIXME: Visit nested-name-specifier.
1094 return false;
1095
1096 case TemplateName::QualifiedTemplate:
1097 // FIXME: Visit nested-name-specifier.
1098 return Visit(MakeCursorTemplateRef(
1099 Name.getAsQualifiedTemplateName()->getDecl(),
1100 Loc, TU));
1101 }
1102
1103 return false;
1104}
1105
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001106bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1107 switch (TAL.getArgument().getKind()) {
1108 case TemplateArgument::Null:
1109 case TemplateArgument::Integral:
1110 return false;
1111
1112 case TemplateArgument::Pack:
1113 // FIXME: Implement when variadic templates come along.
1114 return false;
1115
1116 case TemplateArgument::Type:
1117 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1118 return Visit(TSInfo->getTypeLoc());
1119 return false;
1120
1121 case TemplateArgument::Declaration:
1122 if (Expr *E = TAL.getSourceDeclExpression())
1123 return Visit(MakeCXCursor(E, StmtParent, TU));
1124 return false;
1125
1126 case TemplateArgument::Expression:
1127 if (Expr *E = TAL.getSourceExpression())
1128 return Visit(MakeCXCursor(E, StmtParent, TU));
1129 return false;
1130
1131 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001132 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1133 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001134 }
1135
1136 return false;
1137}
1138
Ted Kremeneka0536d82010-05-07 01:04:29 +00001139bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1140 return VisitDeclContext(D);
1141}
1142
Douglas Gregor01829d32010-08-31 14:41:23 +00001143bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1144 return Visit(TL.getUnqualifiedLoc());
1145}
1146
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001147bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1148 ASTContext &Context = TU->getASTContext();
1149
1150 // Some builtin types (such as Objective-C's "id", "sel", and
1151 // "Class") have associated declarations. Create cursors for those.
1152 QualType VisitType;
1153 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001154 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001155 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001156 case BuiltinType::Char_U:
1157 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001158 case BuiltinType::Char16:
1159 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001160 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001161 case BuiltinType::UInt:
1162 case BuiltinType::ULong:
1163 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001164 case BuiltinType::UInt128:
1165 case BuiltinType::Char_S:
1166 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001167 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001168 case BuiltinType::Short:
1169 case BuiltinType::Int:
1170 case BuiltinType::Long:
1171 case BuiltinType::LongLong:
1172 case BuiltinType::Int128:
1173 case BuiltinType::Float:
1174 case BuiltinType::Double:
1175 case BuiltinType::LongDouble:
1176 case BuiltinType::NullPtr:
1177 case BuiltinType::Overload:
1178 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001179 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001180
1181 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001182 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001183
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001184 case BuiltinType::ObjCId:
1185 VisitType = Context.getObjCIdType();
1186 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001187
1188 case BuiltinType::ObjCClass:
1189 VisitType = Context.getObjCClassType();
1190 break;
1191
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001192 case BuiltinType::ObjCSel:
1193 VisitType = Context.getObjCSelType();
1194 break;
1195 }
1196
1197 if (!VisitType.isNull()) {
1198 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001199 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001200 TU));
1201 }
1202
1203 return false;
1204}
1205
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001206bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1207 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1208}
1209
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001210bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1211 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1212}
1213
1214bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1215 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1216}
1217
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001218bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1219 // FIXME: We can't visit the template template parameter, but there's
1220 // no context information with which we can match up the depth/index in the
1221 // type to the appropriate
1222 return false;
1223}
1224
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001225bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1226 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1227 return true;
1228
John McCallc12c5bb2010-05-15 11:32:37 +00001229 return false;
1230}
1231
1232bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1233 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1234 return true;
1235
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001236 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1237 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1238 TU)))
1239 return true;
1240 }
1241
1242 return false;
1243}
1244
1245bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001246 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001247}
1248
1249bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1250 return Visit(TL.getPointeeLoc());
1251}
1252
1253bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1254 return Visit(TL.getPointeeLoc());
1255}
1256
1257bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1258 return Visit(TL.getPointeeLoc());
1259}
1260
1261bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001262 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001263}
1264
1265bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001266 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001267}
1268
Douglas Gregor01829d32010-08-31 14:41:23 +00001269bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1270 bool SkipResultType) {
1271 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001272 return true;
1273
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001274 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001275 if (Decl *D = TL.getArg(I))
1276 if (Visit(MakeCXCursor(D, TU)))
1277 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001278
1279 return false;
1280}
1281
1282bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1283 if (Visit(TL.getElementLoc()))
1284 return true;
1285
1286 if (Expr *Size = TL.getSizeExpr())
1287 return Visit(MakeCXCursor(Size, StmtParent, TU));
1288
1289 return false;
1290}
1291
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001292bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1293 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001294 // Visit the template name.
1295 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1296 TL.getTemplateNameLoc()))
1297 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001298
1299 // Visit the template arguments.
1300 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1301 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1302 return true;
1303
1304 return false;
1305}
1306
Douglas Gregor2332c112010-01-21 20:48:56 +00001307bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1308 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1309}
1310
1311bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1312 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1313 return Visit(TSInfo->getTypeLoc());
1314
1315 return false;
1316}
1317
Douglas Gregora59e3902010-01-21 23:27:09 +00001318bool CursorVisitor::VisitStmt(Stmt *S) {
1319 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1320 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001321 if (Stmt *C = *Child)
1322 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1323 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001324 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001325
Douglas Gregora59e3902010-01-21 23:27:09 +00001326 return false;
1327}
1328
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001329bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1330 // Specially handle CaseStmts because they can be nested, e.g.:
1331 //
1332 // case 1:
1333 // case 2:
1334 //
1335 // In this case the second CaseStmt is the child of the first. Walking
1336 // these recursively can blow out the stack.
1337 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1338 while (true) {
1339 // Set the Parent field to Cursor, then back to its old value once we're
1340 // done.
1341 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1342
1343 if (Stmt *LHS = S->getLHS())
1344 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1345 return true;
1346 if (Stmt *RHS = S->getRHS())
1347 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1348 return true;
1349 if (Stmt *SubStmt = S->getSubStmt()) {
1350 if (!isa<CaseStmt>(SubStmt))
1351 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1352
1353 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1354 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1355 Cursor = MakeCXCursor(CS, StmtParent, TU);
1356 if (RegionOfInterest.isValid()) {
1357 SourceRange Range = CS->getSourceRange();
1358 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1359 return false;
1360 }
1361
1362 switch (Visitor(Cursor, Parent, ClientData)) {
1363 case CXChildVisit_Break: return true;
1364 case CXChildVisit_Continue: return false;
1365 case CXChildVisit_Recurse:
1366 // Perform tail-recursion manually.
1367 S = CS;
1368 continue;
1369 }
1370 }
1371 return false;
1372 }
1373}
1374
Douglas Gregora59e3902010-01-21 23:27:09 +00001375bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1376 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1377 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001378 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001379 return true;
1380 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001381
Douglas Gregora59e3902010-01-21 23:27:09 +00001382 return false;
1383}
1384
Douglas Gregorf5bab412010-01-22 01:00:11 +00001385bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1386 if (VarDecl *Var = S->getConditionVariable()) {
1387 if (Visit(MakeCXCursor(Var, TU)))
1388 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001389 }
1390
Douglas Gregor263b47b2010-01-25 16:12:32 +00001391 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1392 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001393 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1394 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001395 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1396 return true;
1397
1398 return false;
1399}
1400
1401bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1402 if (VarDecl *Var = S->getConditionVariable()) {
1403 if (Visit(MakeCXCursor(Var, TU)))
1404 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001405 }
1406
Douglas Gregor263b47b2010-01-25 16:12:32 +00001407 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1408 return true;
1409 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1410 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001411
Douglas Gregor263b47b2010-01-25 16:12:32 +00001412 return false;
1413}
1414
1415bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1416 if (VarDecl *Var = S->getConditionVariable()) {
1417 if (Visit(MakeCXCursor(Var, TU)))
1418 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001419 }
1420
Douglas Gregor263b47b2010-01-25 16:12:32 +00001421 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1422 return true;
1423 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001424 return true;
1425
Douglas Gregor263b47b2010-01-25 16:12:32 +00001426 return false;
1427}
1428
1429bool CursorVisitor::VisitForStmt(ForStmt *S) {
1430 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1431 return true;
1432 if (VarDecl *Var = S->getConditionVariable()) {
1433 if (Visit(MakeCXCursor(Var, TU)))
1434 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001435 }
1436
Douglas Gregor263b47b2010-01-25 16:12:32 +00001437 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1438 return true;
1439 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1440 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001441 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1442 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001443
Douglas Gregorf5bab412010-01-22 01:00:11 +00001444 return false;
1445}
1446
Douglas Gregor8947a752010-09-02 20:35:02 +00001447bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1448 // Visit nested-name-specifier, if present.
1449 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1450 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1451 return true;
1452
1453 // Visit declaration name.
1454 if (VisitDeclarationNameInfo(E->getNameInfo()))
1455 return true;
1456
1457 // Visit explicitly-specified template arguments.
1458 if (E->hasExplicitTemplateArgs()) {
1459 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1460 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1461 *ArgEnd = Arg + Args.NumTemplateArgs;
1462 Arg != ArgEnd; ++Arg)
1463 if (VisitTemplateArgumentLoc(*Arg))
1464 return true;
1465 }
1466
1467 return false;
1468}
1469
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001470bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1471 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1472 return true;
1473
1474 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1475 return true;
1476
1477 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1478 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1479 return true;
1480
1481 return false;
1482}
1483
Ted Kremenek3064ef92010-08-27 21:34:58 +00001484bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1485 if (D->isDefinition()) {
1486 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1487 E = D->bases_end(); I != E; ++I) {
1488 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1489 return true;
1490 }
1491 }
1492
1493 return VisitTagDecl(D);
1494}
1495
1496
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001497bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1498 return Visit(B->getBlockDecl());
1499}
1500
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001501bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1502 // FIXME: Visit fields as well?
1503 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1504 return true;
1505
1506 return VisitExpr(E);
1507}
1508
Douglas Gregor336fd812010-01-23 00:40:08 +00001509bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1510 if (E->isArgumentType()) {
1511 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1512 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001513
Douglas Gregor336fd812010-01-23 00:40:08 +00001514 return false;
1515 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001516
Douglas Gregor336fd812010-01-23 00:40:08 +00001517 return VisitExpr(E);
1518}
1519
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001520bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1521 // Visit the base expression.
1522 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1523 return true;
1524
1525 // Visit the nested-name-specifier
1526 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1527 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1528 return true;
1529
1530 // Visit the declaration name.
1531 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1532 return true;
1533
1534 // Visit the explicitly-specified template arguments, if any.
1535 if (E->hasExplicitTemplateArgs()) {
1536 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1537 *ArgEnd = Arg + E->getNumTemplateArgs();
1538 Arg != ArgEnd;
1539 ++Arg) {
1540 if (VisitTemplateArgumentLoc(*Arg))
1541 return true;
1542 }
1543 }
1544
1545 return false;
1546}
1547
Douglas Gregor336fd812010-01-23 00:40:08 +00001548bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1549 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1550 if (Visit(TSInfo->getTypeLoc()))
1551 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001552
Douglas Gregor336fd812010-01-23 00:40:08 +00001553 return VisitCastExpr(E);
1554}
1555
1556bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1557 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1558 if (Visit(TSInfo->getTypeLoc()))
1559 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001560
Douglas Gregor336fd812010-01-23 00:40:08 +00001561 return VisitExpr(E);
1562}
1563
Douglas Gregor648220e2010-08-10 15:02:34 +00001564bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1565 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1566 Visit(E->getArgTInfo2()->getTypeLoc());
1567}
1568
1569bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1570 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1571 return true;
1572
1573 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1574}
1575
Douglas Gregor94802292010-09-02 21:20:16 +00001576bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1577 if (E->isTypeOperand()) {
1578 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1579 return Visit(TSInfo->getTypeLoc());
1580
1581 return false;
1582 }
1583
1584 return VisitExpr(E);
1585}
1586
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001587bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1588 // Visit base expression.
1589 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1590 return true;
1591
1592 // Visit the nested-name-specifier.
1593 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1594 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1595 return true;
1596
1597 // Visit the scope type that looks disturbingly like the nested-name-specifier
1598 // but isn't.
1599 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1600 if (Visit(TSInfo->getTypeLoc()))
1601 return true;
1602
1603 // Visit the name of the type being destroyed.
1604 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1605 if (Visit(TSInfo->getTypeLoc()))
1606 return true;
1607
1608 return false;
1609}
1610
Douglas Gregorc2350e52010-03-08 16:40:19 +00001611bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001612 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1613 if (Visit(TSInfo->getTypeLoc()))
1614 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001615
1616 return VisitExpr(E);
1617}
1618
Douglas Gregor81d34662010-04-20 15:39:42 +00001619bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1620 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1621}
1622
1623
Ted Kremenek09dfa372010-02-18 05:46:33 +00001624bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001625 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1626 i != e; ++i)
1627 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001628 return true;
1629
1630 return false;
1631}
1632
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001633extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001634CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1635 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001636 // We use crash recovery to make some of our APIs more reliable, implicitly
1637 // enable it.
1638 llvm::CrashRecoveryContext::Enable();
1639
Douglas Gregora030b7c2010-01-22 20:35:53 +00001640 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001641 if (excludeDeclarationsFromPCH)
1642 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001643 if (displayDiagnostics)
1644 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001645 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001646}
1647
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001648void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001649 if (CIdx)
1650 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001651 if (getenv("LIBCLANG_TIMING"))
1652 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001653}
1654
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001655void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001656 if (CIdx) {
1657 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1658 CXXIdx->setUseExternalASTGeneration(value);
1659 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001660}
1661
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001662CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001663 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001664 if (!CIdx)
1665 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001666
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001667 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001668
Douglas Gregor28019772010-04-05 23:52:57 +00001669 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001670 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001671 CXXIdx->getOnlyLocalDecls(),
1672 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001673}
1674
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001675unsigned clang_defaultEditingTranslationUnitOptions() {
1676 return CXTranslationUnit_PrecompiledPreamble;
1677}
1678
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001679CXTranslationUnit
1680clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1681 const char *source_filename,
1682 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001683 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001684 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001685 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001686 return clang_parseTranslationUnit(CIdx, source_filename,
1687 command_line_args, num_command_line_args,
1688 unsaved_files, num_unsaved_files,
1689 CXTranslationUnit_DetailedPreprocessingRecord);
1690}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001691
1692struct ParseTranslationUnitInfo {
1693 CXIndex CIdx;
1694 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001695 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001696 int num_command_line_args;
1697 struct CXUnsavedFile *unsaved_files;
1698 unsigned num_unsaved_files;
1699 unsigned options;
1700 CXTranslationUnit result;
1701};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001702static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001703 ParseTranslationUnitInfo *PTUI =
1704 static_cast<ParseTranslationUnitInfo*>(UserData);
1705 CXIndex CIdx = PTUI->CIdx;
1706 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001707 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001708 int num_command_line_args = PTUI->num_command_line_args;
1709 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1710 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1711 unsigned options = PTUI->options;
1712 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001713
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001714 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001715 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001716
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001717 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1718
Douglas Gregor44c181a2010-07-23 00:33:23 +00001719 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001720 bool CompleteTranslationUnit
1721 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001722 bool CacheCodeCompetionResults
1723 = options & CXTranslationUnit_CacheCompletionResults;
1724
Douglas Gregor5352ac02010-01-28 00:27:43 +00001725 // Configure the diagnostics.
1726 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001727 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1728 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001729
Douglas Gregor4db64a42010-01-23 00:14:00 +00001730 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1731 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001732 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001733 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001734 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001735 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1736 Buffer));
1737 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001738
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001739 if (!CXXIdx->getUseExternalASTGeneration()) {
1740 llvm::SmallVector<const char *, 16> Args;
1741
1742 // The 'source_filename' argument is optional. If the caller does not
1743 // specify it then it is assumed that the source file is specified
1744 // in the actual argument list.
1745 if (source_filename)
1746 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001747
1748 // Since the Clang C library is primarily used by batch tools dealing with
1749 // (often very broken) source code, where spell-checking can have a
1750 // significant negative impact on performance (particularly when
1751 // precompiled headers are involved), we disable it by default.
1752 // Note that we place this argument early in the list, so that it can be
1753 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001754 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001755
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001756 Args.insert(Args.end(), command_line_args,
1757 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001758
Douglas Gregor44c181a2010-07-23 00:33:23 +00001759 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001760 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1761 Args.push_back("-Xclang");
1762 Args.push_back("-detailed-preprocessing-record");
1763 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001764
Douglas Gregor5352ac02010-01-28 00:27:43 +00001765 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001766
Ted Kremenek29b72842010-01-07 22:49:05 +00001767#ifdef USE_CRASHTRACER
1768 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001769#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001770
Daniel Dunbar94220972009-12-05 02:17:18 +00001771 llvm::OwningPtr<ASTUnit> Unit(
1772 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001773 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001774 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001775 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001776 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001777 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001778 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001779 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001780 CompleteTranslationUnit,
1781 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001782
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001783 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001784 // Make sure to check that 'Unit' is non-NULL.
1785 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001786 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1787 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001788 D != DEnd; ++D) {
1789 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001790 CXString Msg = clang_formatDiagnostic(&Diag,
1791 clang_defaultDiagnosticDisplayOptions());
1792 fprintf(stderr, "%s\n", clang_getCString(Msg));
1793 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001794 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001795#ifdef LLVM_ON_WIN32
1796 // On Windows, force a flush, since there may be multiple copies of
1797 // stderr and stdout in the file system, all with different buffers
1798 // but writing to the same device.
1799 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001800#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001801 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001802 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001803
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001804 PTUI->result = Unit.take();
1805 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001806 }
1807
Ted Kremenek139ba862009-10-22 00:03:57 +00001808 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001809 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001810
Ted Kremenek139ba862009-10-22 00:03:57 +00001811 // First add the complete path to the 'clang' executable.
1812 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001813 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001814
Ted Kremenek139ba862009-10-22 00:03:57 +00001815 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001816 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001817
Ted Kremenek139ba862009-10-22 00:03:57 +00001818 // The 'source_filename' argument is optional. If the caller does not
1819 // specify it then it is assumed that the source file is specified
1820 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001821 if (source_filename)
1822 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001823
Steve Naroff37b5ac22009-10-15 20:50:09 +00001824 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001825 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001826 char astTmpFile[L_tmpnam];
1827 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001828
1829 // Since the Clang C library is primarily used by batch tools dealing with
1830 // (often very broken) source code, where spell-checking can have a
1831 // significant negative impact on performance (particularly when
1832 // precompiled headers are involved), we disable it by default.
1833 // Note that we place this argument early in the list, so that it can be
1834 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001835 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001836
Douglas Gregor4db64a42010-01-23 00:14:00 +00001837 // Remap any unsaved files to temporary files.
1838 std::vector<llvm::sys::Path> TemporaryFiles;
1839 std::vector<std::string> RemapArgs;
1840 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001841 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001842
Douglas Gregor4db64a42010-01-23 00:14:00 +00001843 // The pointers into the elements of RemapArgs are stable because we
1844 // won't be adding anything to RemapArgs after this point.
1845 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1846 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001847
Ted Kremenek139ba862009-10-22 00:03:57 +00001848 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1849 for (int i = 0; i < num_command_line_args; ++i)
1850 if (const char *arg = command_line_args[i]) {
1851 if (strcmp(arg, "-o") == 0) {
1852 ++i; // Also skip the matching argument.
1853 continue;
1854 }
1855 if (strcmp(arg, "-emit-ast") == 0 ||
1856 strcmp(arg, "-c") == 0 ||
1857 strcmp(arg, "-fsyntax-only") == 0) {
1858 continue;
1859 }
1860
1861 // Keep the argument.
1862 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001863 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001864
Douglas Gregord93256e2010-01-28 06:00:51 +00001865 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001866 char tmpFileResults[L_tmpnam];
1867 char *tmpResultsFileName = tmpnam(tmpFileResults);
1868 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001869 TemporaryFiles.push_back(DiagnosticsFile);
1870 argv.push_back("-fdiagnostics-binary");
1871
Douglas Gregor44c181a2010-07-23 00:33:23 +00001872 // Do we need the detailed preprocessing record?
1873 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1874 argv.push_back("-Xclang");
1875 argv.push_back("-detailed-preprocessing-record");
1876 }
1877
Ted Kremenek139ba862009-10-22 00:03:57 +00001878 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001879 argv.push_back(NULL);
1880
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001881 // Invoke 'clang'.
1882 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1883 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001884 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001885 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1886 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001887 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001888 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001889 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001890
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001891 if (!ErrMsg.empty()) {
1892 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001893 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001894 I != E; ++I) {
1895 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001896 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001897 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001898 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001899
Daniel Dunbar32141c82010-02-23 20:23:45 +00001900 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001901 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001902
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001903 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001904 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001905 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001906 RemappedFiles.size(),
1907 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001908 if (ATU) {
1909 LoadSerializedDiagnostics(DiagnosticsFile,
1910 num_unsaved_files, unsaved_files,
1911 ATU->getFileManager(),
1912 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001913 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001914 } else if (CXXIdx->getDisplayDiagnostics()) {
1915 // We failed to load the ASTUnit, but we can still deserialize the
1916 // diagnostics and emit them.
1917 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001918 Diagnostic Diag;
1919 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001920 // FIXME: Faked LangOpts!
1921 LangOptions LangOpts;
1922 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1923 LoadSerializedDiagnostics(DiagnosticsFile,
1924 num_unsaved_files, unsaved_files,
1925 FileMgr, SourceMgr, Diags);
1926 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1927 DEnd = Diags.end();
1928 D != DEnd; ++D) {
1929 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001930 CXString Msg = clang_formatDiagnostic(&Diag,
1931 clang_defaultDiagnosticDisplayOptions());
1932 fprintf(stderr, "%s\n", clang_getCString(Msg));
1933 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001934 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001935
1936#ifdef LLVM_ON_WIN32
1937 // On Windows, force a flush, since there may be multiple copies of
1938 // stderr and stdout in the file system, all with different buffers
1939 // but writing to the same device.
1940 fflush(stderr);
1941#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001942 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001943
Douglas Gregor313e26c2010-02-18 23:35:40 +00001944 if (ATU) {
1945 // Make the translation unit responsible for destroying all temporary files.
1946 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1947 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001948 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001949 } else {
1950 // Destroy all of the temporary files now; they can't be referenced any
1951 // longer.
1952 llvm::sys::Path(astTmpFile).eraseFromDisk();
1953 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1954 TemporaryFiles[i].eraseFromDisk();
1955 }
1956
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001957 PTUI->result = ATU;
1958}
1959CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1960 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001961 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001962 int num_command_line_args,
1963 struct CXUnsavedFile *unsaved_files,
1964 unsigned num_unsaved_files,
1965 unsigned options) {
1966 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1967 num_command_line_args, unsaved_files, num_unsaved_files,
1968 options, 0 };
1969 llvm::CrashRecoveryContext CRC;
1970
1971 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001972 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1973 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1974 fprintf(stderr, " 'command_line_args' : [");
1975 for (int i = 0; i != num_command_line_args; ++i) {
1976 if (i)
1977 fprintf(stderr, ", ");
1978 fprintf(stderr, "'%s'", command_line_args[i]);
1979 }
1980 fprintf(stderr, "],\n");
1981 fprintf(stderr, " 'unsaved_files' : [");
1982 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1983 if (i)
1984 fprintf(stderr, ", ");
1985 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1986 unsaved_files[i].Length);
1987 }
1988 fprintf(stderr, "],\n");
1989 fprintf(stderr, " 'options' : %d,\n", options);
1990 fprintf(stderr, "}\n");
1991
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001992 return 0;
1993 }
1994
1995 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001996}
1997
Douglas Gregor19998442010-08-13 15:35:05 +00001998unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1999 return CXSaveTranslationUnit_None;
2000}
2001
2002int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2003 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002004 if (!TU)
2005 return 1;
2006
2007 return static_cast<ASTUnit *>(TU)->Save(FileName);
2008}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002009
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002010void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002011 if (CTUnit) {
2012 // If the translation unit has been marked as unsafe to free, just discard
2013 // it.
2014 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2015 return;
2016
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002017 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002018 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002019}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002020
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002021unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2022 return CXReparse_None;
2023}
2024
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002025struct ReparseTranslationUnitInfo {
2026 CXTranslationUnit TU;
2027 unsigned num_unsaved_files;
2028 struct CXUnsavedFile *unsaved_files;
2029 unsigned options;
2030 int result;
2031};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002032static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002033 ReparseTranslationUnitInfo *RTUI =
2034 static_cast<ReparseTranslationUnitInfo*>(UserData);
2035 CXTranslationUnit TU = RTUI->TU;
2036 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2037 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2038 unsigned options = RTUI->options;
2039 (void) options;
2040 RTUI->result = 1;
2041
Douglas Gregorabc563f2010-07-19 21:46:24 +00002042 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002043 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002044
2045 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2046 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2047 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2048 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002049 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002050 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2051 Buffer));
2052 }
2053
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002054 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
2055 RemappedFiles.size()))
2056 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002057}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002058int clang_reparseTranslationUnit(CXTranslationUnit TU,
2059 unsigned num_unsaved_files,
2060 struct CXUnsavedFile *unsaved_files,
2061 unsigned options) {
2062 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2063 options, 0 };
2064 llvm::CrashRecoveryContext CRC;
2065
2066 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002067 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002068 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2069 return 1;
2070 }
2071
2072 return RTUI.result;
2073}
2074
Douglas Gregordf95a132010-08-09 20:45:32 +00002075
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002076CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002077 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002078 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002079
Steve Naroff77accc12009-09-03 18:19:54 +00002080 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002081 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002082}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002083
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002084CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002085 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002086 return Result;
2087}
2088
Ted Kremenekfb480492010-01-13 21:46:36 +00002089} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002090
Ted Kremenekfb480492010-01-13 21:46:36 +00002091//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002092// CXSourceLocation and CXSourceRange Operations.
2093//===----------------------------------------------------------------------===//
2094
Douglas Gregorb9790342010-01-22 21:44:22 +00002095extern "C" {
2096CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002097 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002098 return Result;
2099}
2100
2101unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002102 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2103 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2104 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002105}
2106
2107CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2108 CXFile file,
2109 unsigned line,
2110 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002111 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002112 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002113
Douglas Gregorb9790342010-01-22 21:44:22 +00002114 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2115 SourceLocation SLoc
2116 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002117 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002118 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002119
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002120 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002121}
2122
Douglas Gregor5352ac02010-01-28 00:27:43 +00002123CXSourceRange clang_getNullRange() {
2124 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2125 return Result;
2126}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002127
Douglas Gregor5352ac02010-01-28 00:27:43 +00002128CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2129 if (begin.ptr_data[0] != end.ptr_data[0] ||
2130 begin.ptr_data[1] != end.ptr_data[1])
2131 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002132
2133 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002134 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002135 return Result;
2136}
2137
Douglas Gregor46766dc2010-01-26 19:19:08 +00002138void clang_getInstantiationLocation(CXSourceLocation location,
2139 CXFile *file,
2140 unsigned *line,
2141 unsigned *column,
2142 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002143 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2144
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002145 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002146 if (file)
2147 *file = 0;
2148 if (line)
2149 *line = 0;
2150 if (column)
2151 *column = 0;
2152 if (offset)
2153 *offset = 0;
2154 return;
2155 }
2156
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002157 const SourceManager &SM =
2158 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002159 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002160
2161 if (file)
2162 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2163 if (line)
2164 *line = SM.getInstantiationLineNumber(InstLoc);
2165 if (column)
2166 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002167 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002168 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002169}
2170
Douglas Gregor1db19de2010-01-19 21:36:55 +00002171CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002172 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002173 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002174 return Result;
2175}
2176
2177CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002178 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002179 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002180 return Result;
2181}
2182
Douglas Gregorb9790342010-01-22 21:44:22 +00002183} // end: extern "C"
2184
Douglas Gregor1db19de2010-01-19 21:36:55 +00002185//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002186// CXFile Operations.
2187//===----------------------------------------------------------------------===//
2188
2189extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002190CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002191 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002192 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002193
Steve Naroff88145032009-10-27 14:35:18 +00002194 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002195 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002196}
2197
2198time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002199 if (!SFile)
2200 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002201
Steve Naroff88145032009-10-27 14:35:18 +00002202 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2203 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002204}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002205
Douglas Gregorb9790342010-01-22 21:44:22 +00002206CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2207 if (!tu)
2208 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002209
Douglas Gregorb9790342010-01-22 21:44:22 +00002210 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002211
Douglas Gregorb9790342010-01-22 21:44:22 +00002212 FileManager &FMgr = CXXUnit->getFileManager();
2213 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2214 return const_cast<FileEntry *>(File);
2215}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002216
Ted Kremenekfb480492010-01-13 21:46:36 +00002217} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002218
Ted Kremenekfb480492010-01-13 21:46:36 +00002219//===----------------------------------------------------------------------===//
2220// CXCursor Operations.
2221//===----------------------------------------------------------------------===//
2222
Ted Kremenekfb480492010-01-13 21:46:36 +00002223static Decl *getDeclFromExpr(Stmt *E) {
2224 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2225 return RefExpr->getDecl();
2226 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2227 return ME->getMemberDecl();
2228 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2229 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002230
Ted Kremenekfb480492010-01-13 21:46:36 +00002231 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2232 return getDeclFromExpr(CE->getCallee());
2233 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2234 return getDeclFromExpr(CE->getSubExpr());
2235 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2236 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002237
Ted Kremenekfb480492010-01-13 21:46:36 +00002238 return 0;
2239}
2240
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002241static SourceLocation getLocationFromExpr(Expr *E) {
2242 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2243 return /*FIXME:*/Msg->getLeftLoc();
2244 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2245 return DRE->getLocation();
2246 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2247 return Member->getMemberLoc();
2248 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2249 return Ivar->getLocation();
2250 return E->getLocStart();
2251}
2252
Ted Kremenekfb480492010-01-13 21:46:36 +00002253extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002254
2255unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002256 CXCursorVisitor visitor,
2257 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002258 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002259
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002260 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2261 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002262 return CursorVis.VisitChildren(parent);
2263}
2264
Douglas Gregor78205d42010-01-20 21:45:58 +00002265static CXString getDeclSpelling(Decl *D) {
2266 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2267 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002268 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002269
Douglas Gregor78205d42010-01-20 21:45:58 +00002270 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002271 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002272
Douglas Gregor78205d42010-01-20 21:45:58 +00002273 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2274 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2275 // and returns different names. NamedDecl returns the class name and
2276 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002277 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002278
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002279 if (isa<UsingDirectiveDecl>(D))
2280 return createCXString("");
2281
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002282 llvm::SmallString<1024> S;
2283 llvm::raw_svector_ostream os(S);
2284 ND->printName(os);
2285
2286 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002287}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002288
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002289CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002290 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002291 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002292
Steve Narofff334b4e2009-09-02 18:26:48 +00002293 if (clang_isReference(C.kind)) {
2294 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002295 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002296 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002297 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002298 }
2299 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002300 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002301 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002302 }
2303 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002304 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002305 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002306 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002307 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002308 case CXCursor_CXXBaseSpecifier: {
2309 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2310 return createCXString(B->getType().getAsString());
2311 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002312 case CXCursor_TypeRef: {
2313 TypeDecl *Type = getCursorTypeRef(C).first;
2314 assert(Type && "Missing type decl");
2315
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002316 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2317 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002318 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002319 case CXCursor_TemplateRef: {
2320 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002321 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002322
2323 return createCXString(Template->getNameAsString());
2324 }
Douglas Gregor69319002010-08-31 23:48:11 +00002325
2326 case CXCursor_NamespaceRef: {
2327 NamedDecl *NS = getCursorNamespaceRef(C).first;
2328 assert(NS && "Missing namespace decl");
2329
2330 return createCXString(NS->getNameAsString());
2331 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002332
Daniel Dunbaracca7252009-11-30 20:42:49 +00002333 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002334 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002335 }
2336 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002337
2338 if (clang_isExpression(C.kind)) {
2339 Decl *D = getDeclFromExpr(getCursorExpr(C));
2340 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002341 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002342 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002343 }
2344
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002345 if (C.kind == CXCursor_MacroInstantiation)
2346 return createCXString(getCursorMacroInstantiation(C)->getName()
2347 ->getNameStart());
2348
Douglas Gregor572feb22010-03-18 18:04:21 +00002349 if (C.kind == CXCursor_MacroDefinition)
2350 return createCXString(getCursorMacroDefinition(C)->getName()
2351 ->getNameStart());
2352
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002353 if (clang_isDeclaration(C.kind))
2354 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002355
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002356 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002357}
2358
Ted Kremeneke68fff62010-02-17 00:41:32 +00002359CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002360 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002361 case CXCursor_FunctionDecl:
2362 return createCXString("FunctionDecl");
2363 case CXCursor_TypedefDecl:
2364 return createCXString("TypedefDecl");
2365 case CXCursor_EnumDecl:
2366 return createCXString("EnumDecl");
2367 case CXCursor_EnumConstantDecl:
2368 return createCXString("EnumConstantDecl");
2369 case CXCursor_StructDecl:
2370 return createCXString("StructDecl");
2371 case CXCursor_UnionDecl:
2372 return createCXString("UnionDecl");
2373 case CXCursor_ClassDecl:
2374 return createCXString("ClassDecl");
2375 case CXCursor_FieldDecl:
2376 return createCXString("FieldDecl");
2377 case CXCursor_VarDecl:
2378 return createCXString("VarDecl");
2379 case CXCursor_ParmDecl:
2380 return createCXString("ParmDecl");
2381 case CXCursor_ObjCInterfaceDecl:
2382 return createCXString("ObjCInterfaceDecl");
2383 case CXCursor_ObjCCategoryDecl:
2384 return createCXString("ObjCCategoryDecl");
2385 case CXCursor_ObjCProtocolDecl:
2386 return createCXString("ObjCProtocolDecl");
2387 case CXCursor_ObjCPropertyDecl:
2388 return createCXString("ObjCPropertyDecl");
2389 case CXCursor_ObjCIvarDecl:
2390 return createCXString("ObjCIvarDecl");
2391 case CXCursor_ObjCInstanceMethodDecl:
2392 return createCXString("ObjCInstanceMethodDecl");
2393 case CXCursor_ObjCClassMethodDecl:
2394 return createCXString("ObjCClassMethodDecl");
2395 case CXCursor_ObjCImplementationDecl:
2396 return createCXString("ObjCImplementationDecl");
2397 case CXCursor_ObjCCategoryImplDecl:
2398 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002399 case CXCursor_CXXMethod:
2400 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002401 case CXCursor_UnexposedDecl:
2402 return createCXString("UnexposedDecl");
2403 case CXCursor_ObjCSuperClassRef:
2404 return createCXString("ObjCSuperClassRef");
2405 case CXCursor_ObjCProtocolRef:
2406 return createCXString("ObjCProtocolRef");
2407 case CXCursor_ObjCClassRef:
2408 return createCXString("ObjCClassRef");
2409 case CXCursor_TypeRef:
2410 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002411 case CXCursor_TemplateRef:
2412 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002413 case CXCursor_NamespaceRef:
2414 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002415 case CXCursor_UnexposedExpr:
2416 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002417 case CXCursor_BlockExpr:
2418 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002419 case CXCursor_DeclRefExpr:
2420 return createCXString("DeclRefExpr");
2421 case CXCursor_MemberRefExpr:
2422 return createCXString("MemberRefExpr");
2423 case CXCursor_CallExpr:
2424 return createCXString("CallExpr");
2425 case CXCursor_ObjCMessageExpr:
2426 return createCXString("ObjCMessageExpr");
2427 case CXCursor_UnexposedStmt:
2428 return createCXString("UnexposedStmt");
2429 case CXCursor_InvalidFile:
2430 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002431 case CXCursor_InvalidCode:
2432 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002433 case CXCursor_NoDeclFound:
2434 return createCXString("NoDeclFound");
2435 case CXCursor_NotImplemented:
2436 return createCXString("NotImplemented");
2437 case CXCursor_TranslationUnit:
2438 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002439 case CXCursor_UnexposedAttr:
2440 return createCXString("UnexposedAttr");
2441 case CXCursor_IBActionAttr:
2442 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002443 case CXCursor_IBOutletAttr:
2444 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002445 case CXCursor_IBOutletCollectionAttr:
2446 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002447 case CXCursor_PreprocessingDirective:
2448 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002449 case CXCursor_MacroDefinition:
2450 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002451 case CXCursor_MacroInstantiation:
2452 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002453 case CXCursor_Namespace:
2454 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002455 case CXCursor_LinkageSpec:
2456 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002457 case CXCursor_CXXBaseSpecifier:
2458 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002459 case CXCursor_Constructor:
2460 return createCXString("CXXConstructor");
2461 case CXCursor_Destructor:
2462 return createCXString("CXXDestructor");
2463 case CXCursor_ConversionFunction:
2464 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002465 case CXCursor_TemplateTypeParameter:
2466 return createCXString("TemplateTypeParameter");
2467 case CXCursor_NonTypeTemplateParameter:
2468 return createCXString("NonTypeTemplateParameter");
2469 case CXCursor_TemplateTemplateParameter:
2470 return createCXString("TemplateTemplateParameter");
2471 case CXCursor_FunctionTemplate:
2472 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002473 case CXCursor_ClassTemplate:
2474 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002475 case CXCursor_ClassTemplatePartialSpecialization:
2476 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002477 case CXCursor_NamespaceAlias:
2478 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002479 case CXCursor_UsingDirective:
2480 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002481 case CXCursor_UsingDeclaration:
2482 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002483 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002484
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002485 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002486 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002487}
Steve Naroff89922f82009-08-31 00:59:03 +00002488
Ted Kremeneke68fff62010-02-17 00:41:32 +00002489enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2490 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002491 CXClientData client_data) {
2492 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2493 *BestCursor = cursor;
2494 return CXChildVisit_Recurse;
2495}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002496
Douglas Gregorb9790342010-01-22 21:44:22 +00002497CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2498 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002499 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002500
Douglas Gregorb9790342010-01-22 21:44:22 +00002501 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002502 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2503
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002504 // Translate the given source location to make it point at the beginning of
2505 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002506 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002507
2508 // Guard against an invalid SourceLocation, or we may assert in one
2509 // of the following calls.
2510 if (SLoc.isInvalid())
2511 return clang_getNullCursor();
2512
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002513 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2514 CXXUnit->getASTContext().getLangOptions());
2515
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002516 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2517 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002518 // FIXME: Would be great to have a "hint" cursor, then walk from that
2519 // hint cursor upward until we find a cursor whose source range encloses
2520 // the region of interest, rather than starting from the translation unit.
2521 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002522 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002523 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002524 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002525 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002526 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002527}
2528
Ted Kremenek73885552009-11-17 19:28:59 +00002529CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002530 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002531}
2532
2533unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002534 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002535}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002536
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002537unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002538 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2539}
2540
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002541unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002542 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2543}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002544
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002545unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002546 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2547}
2548
Douglas Gregor97b98722010-01-19 23:20:36 +00002549unsigned clang_isExpression(enum CXCursorKind K) {
2550 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2551}
2552
2553unsigned clang_isStatement(enum CXCursorKind K) {
2554 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2555}
2556
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002557unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2558 return K == CXCursor_TranslationUnit;
2559}
2560
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002561unsigned clang_isPreprocessing(enum CXCursorKind K) {
2562 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2563}
2564
Ted Kremenekad6eff62010-03-08 21:17:29 +00002565unsigned clang_isUnexposed(enum CXCursorKind K) {
2566 switch (K) {
2567 case CXCursor_UnexposedDecl:
2568 case CXCursor_UnexposedExpr:
2569 case CXCursor_UnexposedStmt:
2570 case CXCursor_UnexposedAttr:
2571 return true;
2572 default:
2573 return false;
2574 }
2575}
2576
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002577CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002578 return C.kind;
2579}
2580
Douglas Gregor98258af2010-01-18 22:46:11 +00002581CXSourceLocation clang_getCursorLocation(CXCursor C) {
2582 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002583 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002584 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002585 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2586 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002587 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002588 }
2589
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002590 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002591 std::pair<ObjCProtocolDecl *, SourceLocation> P
2592 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002593 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002594 }
2595
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002596 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002597 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2598 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002599 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002600 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002601
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002602 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002603 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002604 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002605 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002606
2607 case CXCursor_TemplateRef: {
2608 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2609 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2610 }
2611
Douglas Gregor69319002010-08-31 23:48:11 +00002612 case CXCursor_NamespaceRef: {
2613 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2614 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2615 }
2616
Ted Kremenek3064ef92010-08-27 21:34:58 +00002617 case CXCursor_CXXBaseSpecifier: {
2618 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2619 return clang_getNullLocation();
2620 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002621
Douglas Gregorf46034a2010-01-18 23:41:10 +00002622 default:
2623 // FIXME: Need a way to enumerate all non-reference cases.
2624 llvm_unreachable("Missed a reference kind");
2625 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002626 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002627
2628 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002629 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002630 getLocationFromExpr(getCursorExpr(C)));
2631
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002632 if (C.kind == CXCursor_PreprocessingDirective) {
2633 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2634 return cxloc::translateSourceLocation(getCursorContext(C), L);
2635 }
Douglas Gregor48072312010-03-18 15:23:44 +00002636
2637 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002638 SourceLocation L
2639 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002640 return cxloc::translateSourceLocation(getCursorContext(C), L);
2641 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002642
2643 if (C.kind == CXCursor_MacroDefinition) {
2644 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2645 return cxloc::translateSourceLocation(getCursorContext(C), L);
2646 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002647
Ted Kremenek9a700d22010-05-12 06:16:13 +00002648 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002649 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002650
Douglas Gregorf46034a2010-01-18 23:41:10 +00002651 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002652 SourceLocation Loc = D->getLocation();
2653 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2654 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002655 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002656}
Douglas Gregora7bde202010-01-19 00:34:46 +00002657
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002658} // end extern "C"
2659
2660static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002661 if (clang_isReference(C.kind)) {
2662 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002663 case CXCursor_ObjCSuperClassRef:
2664 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002665
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002666 case CXCursor_ObjCProtocolRef:
2667 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002668
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002669 case CXCursor_ObjCClassRef:
2670 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002671
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002672 case CXCursor_TypeRef:
2673 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002674
2675 case CXCursor_TemplateRef:
2676 return getCursorTemplateRef(C).second;
2677
Douglas Gregor69319002010-08-31 23:48:11 +00002678 case CXCursor_NamespaceRef:
2679 return getCursorNamespaceRef(C).second;
2680
Ted Kremenek3064ef92010-08-27 21:34:58 +00002681 case CXCursor_CXXBaseSpecifier:
2682 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2683 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002684
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002685 default:
2686 // FIXME: Need a way to enumerate all non-reference cases.
2687 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002688 }
2689 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002690
2691 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002692 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002693
2694 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002695 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002696
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002697 if (C.kind == CXCursor_PreprocessingDirective)
2698 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002699
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002700 if (C.kind == CXCursor_MacroInstantiation)
2701 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002702
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002703 if (C.kind == CXCursor_MacroDefinition)
2704 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002705
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002706 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2707 return getCursorDecl(C)->getSourceRange();
2708
2709 return SourceRange();
2710}
2711
2712extern "C" {
2713
2714CXSourceRange clang_getCursorExtent(CXCursor C) {
2715 SourceRange R = getRawCursorExtent(C);
2716 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002717 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002718
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002719 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002720}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002721
2722CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002723 if (clang_isInvalid(C.kind))
2724 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002725
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002726 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002727 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002728 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002729
Douglas Gregor97b98722010-01-19 23:20:36 +00002730 if (clang_isExpression(C.kind)) {
2731 Decl *D = getDeclFromExpr(getCursorExpr(C));
2732 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002733 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002734 return clang_getNullCursor();
2735 }
2736
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002737 if (C.kind == CXCursor_MacroInstantiation) {
2738 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2739 return MakeMacroDefinitionCursor(Def, CXXUnit);
2740 }
2741
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002742 if (!clang_isReference(C.kind))
2743 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002744
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002745 switch (C.kind) {
2746 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002747 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002748
2749 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002750 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002751
2752 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002753 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002754
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002755 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002756 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002757
2758 case CXCursor_TemplateRef:
2759 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2760
Douglas Gregor69319002010-08-31 23:48:11 +00002761 case CXCursor_NamespaceRef:
2762 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2763
Ted Kremenek3064ef92010-08-27 21:34:58 +00002764 case CXCursor_CXXBaseSpecifier: {
2765 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2766 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2767 CXXUnit));
2768 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002769
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002770 default:
2771 // We would prefer to enumerate all non-reference cursor kinds here.
2772 llvm_unreachable("Unhandled reference cursor kind");
2773 break;
2774 }
2775 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002776
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002777 return clang_getNullCursor();
2778}
2779
Douglas Gregorb6998662010-01-19 19:34:47 +00002780CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002781 if (clang_isInvalid(C.kind))
2782 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002783
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002784 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002785
Douglas Gregorb6998662010-01-19 19:34:47 +00002786 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002787 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002788 C = clang_getCursorReferenced(C);
2789 WasReference = true;
2790 }
2791
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002792 if (C.kind == CXCursor_MacroInstantiation)
2793 return clang_getCursorReferenced(C);
2794
Douglas Gregorb6998662010-01-19 19:34:47 +00002795 if (!clang_isDeclaration(C.kind))
2796 return clang_getNullCursor();
2797
2798 Decl *D = getCursorDecl(C);
2799 if (!D)
2800 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002801
Douglas Gregorb6998662010-01-19 19:34:47 +00002802 switch (D->getKind()) {
2803 // Declaration kinds that don't really separate the notions of
2804 // declaration and definition.
2805 case Decl::Namespace:
2806 case Decl::Typedef:
2807 case Decl::TemplateTypeParm:
2808 case Decl::EnumConstant:
2809 case Decl::Field:
2810 case Decl::ObjCIvar:
2811 case Decl::ObjCAtDefsField:
2812 case Decl::ImplicitParam:
2813 case Decl::ParmVar:
2814 case Decl::NonTypeTemplateParm:
2815 case Decl::TemplateTemplateParm:
2816 case Decl::ObjCCategoryImpl:
2817 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002818 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002819 case Decl::LinkageSpec:
2820 case Decl::ObjCPropertyImpl:
2821 case Decl::FileScopeAsm:
2822 case Decl::StaticAssert:
2823 case Decl::Block:
2824 return C;
2825
2826 // Declaration kinds that don't make any sense here, but are
2827 // nonetheless harmless.
2828 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002829 break;
2830
2831 // Declaration kinds for which the definition is not resolvable.
2832 case Decl::UnresolvedUsingTypename:
2833 case Decl::UnresolvedUsingValue:
2834 break;
2835
2836 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002837 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2838 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002839
2840 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002841 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002842
2843 case Decl::Enum:
2844 case Decl::Record:
2845 case Decl::CXXRecord:
2846 case Decl::ClassTemplateSpecialization:
2847 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002848 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002849 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002850 return clang_getNullCursor();
2851
2852 case Decl::Function:
2853 case Decl::CXXMethod:
2854 case Decl::CXXConstructor:
2855 case Decl::CXXDestructor:
2856 case Decl::CXXConversion: {
2857 const FunctionDecl *Def = 0;
2858 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002859 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002860 return clang_getNullCursor();
2861 }
2862
2863 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002864 // Ask the variable if it has a definition.
2865 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2866 return MakeCXCursor(Def, CXXUnit);
2867 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002868 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002869
Douglas Gregorb6998662010-01-19 19:34:47 +00002870 case Decl::FunctionTemplate: {
2871 const FunctionDecl *Def = 0;
2872 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002873 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002874 return clang_getNullCursor();
2875 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002876
Douglas Gregorb6998662010-01-19 19:34:47 +00002877 case Decl::ClassTemplate: {
2878 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002879 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002880 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002881 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002882 return clang_getNullCursor();
2883 }
2884
2885 case Decl::Using: {
2886 UsingDecl *Using = cast<UsingDecl>(D);
2887 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002888 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2889 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002890 S != SEnd; ++S) {
2891 if (Def != clang_getNullCursor()) {
2892 // FIXME: We have no way to return multiple results.
2893 return clang_getNullCursor();
2894 }
2895
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002896 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002897 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002898 }
2899
2900 return Def;
2901 }
2902
2903 case Decl::UsingShadow:
2904 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002905 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002906 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002907
2908 case Decl::ObjCMethod: {
2909 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2910 if (Method->isThisDeclarationADefinition())
2911 return C;
2912
2913 // Dig out the method definition in the associated
2914 // @implementation, if we have it.
2915 // FIXME: The ASTs should make finding the definition easier.
2916 if (ObjCInterfaceDecl *Class
2917 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2918 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2919 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2920 Method->isInstanceMethod()))
2921 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002922 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002923
2924 return clang_getNullCursor();
2925 }
2926
2927 case Decl::ObjCCategory:
2928 if (ObjCCategoryImplDecl *Impl
2929 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002930 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002931 return clang_getNullCursor();
2932
2933 case Decl::ObjCProtocol:
2934 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2935 return C;
2936 return clang_getNullCursor();
2937
2938 case Decl::ObjCInterface:
2939 // There are two notions of a "definition" for an Objective-C
2940 // class: the interface and its implementation. When we resolved a
2941 // reference to an Objective-C class, produce the @interface as
2942 // the definition; when we were provided with the interface,
2943 // produce the @implementation as the definition.
2944 if (WasReference) {
2945 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2946 return C;
2947 } else if (ObjCImplementationDecl *Impl
2948 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002949 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002950 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002951
Douglas Gregorb6998662010-01-19 19:34:47 +00002952 case Decl::ObjCProperty:
2953 // FIXME: We don't really know where to find the
2954 // ObjCPropertyImplDecls that implement this property.
2955 return clang_getNullCursor();
2956
2957 case Decl::ObjCCompatibleAlias:
2958 if (ObjCInterfaceDecl *Class
2959 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2960 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002961 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002962
Douglas Gregorb6998662010-01-19 19:34:47 +00002963 return clang_getNullCursor();
2964
2965 case Decl::ObjCForwardProtocol: {
2966 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2967 if (Forward->protocol_size() == 1)
2968 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002969 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002970 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002971
2972 // FIXME: Cannot return multiple definitions.
2973 return clang_getNullCursor();
2974 }
2975
2976 case Decl::ObjCClass: {
2977 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2978 if (Class->size() == 1) {
2979 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2980 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002981 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002982 return clang_getNullCursor();
2983 }
2984
2985 // FIXME: Cannot return multiple definitions.
2986 return clang_getNullCursor();
2987 }
2988
2989 case Decl::Friend:
2990 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002991 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002992 return clang_getNullCursor();
2993
2994 case Decl::FriendTemplate:
2995 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002996 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002997 return clang_getNullCursor();
2998 }
2999
3000 return clang_getNullCursor();
3001}
3002
3003unsigned clang_isCursorDefinition(CXCursor C) {
3004 if (!clang_isDeclaration(C.kind))
3005 return 0;
3006
3007 return clang_getCursorDefinition(C) == C;
3008}
3009
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003010void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003011 const char **startBuf,
3012 const char **endBuf,
3013 unsigned *startLine,
3014 unsigned *startColumn,
3015 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003016 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003017 assert(getCursorDecl(C) && "CXCursor has null decl");
3018 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003019 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3020 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003021
Steve Naroff4ade6d62009-09-23 17:52:52 +00003022 SourceManager &SM = FD->getASTContext().getSourceManager();
3023 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3024 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3025 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3026 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3027 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3028 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3029}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003030
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003031void clang_enableStackTraces(void) {
3032 llvm::sys::PrintStackTraceOnErrorSignal();
3033}
3034
Ted Kremenekfb480492010-01-13 21:46:36 +00003035} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003036
Ted Kremenekfb480492010-01-13 21:46:36 +00003037//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003038// Token-based Operations.
3039//===----------------------------------------------------------------------===//
3040
3041/* CXToken layout:
3042 * int_data[0]: a CXTokenKind
3043 * int_data[1]: starting token location
3044 * int_data[2]: token length
3045 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003046 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003047 * otherwise unused.
3048 */
3049extern "C" {
3050
3051CXTokenKind clang_getTokenKind(CXToken CXTok) {
3052 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3053}
3054
3055CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3056 switch (clang_getTokenKind(CXTok)) {
3057 case CXToken_Identifier:
3058 case CXToken_Keyword:
3059 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003060 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3061 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003062
3063 case CXToken_Literal: {
3064 // We have stashed the starting pointer in the ptr_data field. Use it.
3065 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003066 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003067 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003068
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003069 case CXToken_Punctuation:
3070 case CXToken_Comment:
3071 break;
3072 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003073
3074 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003075 // deconstructing the source location.
3076 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3077 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003078 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003079
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003080 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3081 std::pair<FileID, unsigned> LocInfo
3082 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003083 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003084 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003085 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3086 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003087 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003088
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003089 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003090}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003091
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003092CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3093 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3094 if (!CXXUnit)
3095 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003096
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003097 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3098 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3099}
3100
3101CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3102 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003103 if (!CXXUnit)
3104 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003105
3106 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003107 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3108}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003109
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003110void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3111 CXToken **Tokens, unsigned *NumTokens) {
3112 if (Tokens)
3113 *Tokens = 0;
3114 if (NumTokens)
3115 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003116
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003117 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3118 if (!CXXUnit || !Tokens || !NumTokens)
3119 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003120
Douglas Gregorbdf60622010-03-05 21:16:25 +00003121 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3122
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003123 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003124 if (R.isInvalid())
3125 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003126
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003127 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3128 std::pair<FileID, unsigned> BeginLocInfo
3129 = SourceMgr.getDecomposedLoc(R.getBegin());
3130 std::pair<FileID, unsigned> EndLocInfo
3131 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003132
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003133 // Cannot tokenize across files.
3134 if (BeginLocInfo.first != EndLocInfo.first)
3135 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003136
3137 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003138 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003139 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003140 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003141 if (Invalid)
3142 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003143
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003144 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3145 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003146 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003147 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003148
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003149 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003150 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003151 llvm::SmallVector<CXToken, 32> CXTokens;
3152 Token Tok;
3153 do {
3154 // Lex the next token
3155 Lex.LexFromRawLexer(Tok);
3156 if (Tok.is(tok::eof))
3157 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003158
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003159 // Initialize the CXToken.
3160 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003161
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003162 // - Common fields
3163 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3164 CXTok.int_data[2] = Tok.getLength();
3165 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003166
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003167 // - Kind-specific fields
3168 if (Tok.isLiteral()) {
3169 CXTok.int_data[0] = CXToken_Literal;
3170 CXTok.ptr_data = (void *)Tok.getLiteralData();
3171 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003172 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003173 std::pair<FileID, unsigned> LocInfo
3174 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003175 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003176 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003177 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3178 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003179 return;
3180
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003181 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003182 IdentifierInfo *II
3183 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003184
3185 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3186 CXTok.int_data[0] = CXToken_Keyword;
3187 }
3188 else {
3189 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3190 CXToken_Identifier
3191 : CXToken_Keyword;
3192 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003193 CXTok.ptr_data = II;
3194 } else if (Tok.is(tok::comment)) {
3195 CXTok.int_data[0] = CXToken_Comment;
3196 CXTok.ptr_data = 0;
3197 } else {
3198 CXTok.int_data[0] = CXToken_Punctuation;
3199 CXTok.ptr_data = 0;
3200 }
3201 CXTokens.push_back(CXTok);
3202 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003203
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003204 if (CXTokens.empty())
3205 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003206
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003207 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3208 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3209 *NumTokens = CXTokens.size();
3210}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003211
Ted Kremenek6db61092010-05-05 00:55:15 +00003212void clang_disposeTokens(CXTranslationUnit TU,
3213 CXToken *Tokens, unsigned NumTokens) {
3214 free(Tokens);
3215}
3216
3217} // end: extern "C"
3218
3219//===----------------------------------------------------------------------===//
3220// Token annotation APIs.
3221//===----------------------------------------------------------------------===//
3222
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003223typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003224static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3225 CXCursor parent,
3226 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003227namespace {
3228class AnnotateTokensWorker {
3229 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003230 CXToken *Tokens;
3231 CXCursor *Cursors;
3232 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003233 unsigned TokIdx;
3234 CursorVisitor AnnotateVis;
3235 SourceManager &SrcMgr;
3236
3237 bool MoreTokens() const { return TokIdx < NumTokens; }
3238 unsigned NextToken() const { return TokIdx; }
3239 void AdvanceToken() { ++TokIdx; }
3240 SourceLocation GetTokenLoc(unsigned tokI) {
3241 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3242 }
3243
Ted Kremenek6db61092010-05-05 00:55:15 +00003244public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003245 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003246 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3247 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003248 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003249 NumTokens(numTokens), TokIdx(0),
3250 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3251 Decl::MaxPCHLevel, RegionOfInterest),
3252 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003253
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003254 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003255 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003256 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003257};
3258}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003259
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003260void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3261 // Walk the AST within the region of interest, annotating tokens
3262 // along the way.
3263 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003264
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003265 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3266 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3267 if (Pos != Annotated.end())
3268 Cursors[I] = Pos->second;
3269 }
3270
3271 // Finish up annotating any tokens left.
3272 if (!MoreTokens())
3273 return;
3274
3275 const CXCursor &C = clang_getNullCursor();
3276 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3277 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3278 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003279 }
3280}
3281
Ted Kremenek6db61092010-05-05 00:55:15 +00003282enum CXChildVisitResult
3283AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003284 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3285 // We can always annotate a preprocessing directive/macro instantiation.
3286 if (clang_isPreprocessing(cursor.kind)) {
3287 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003288 return CXChildVisit_Recurse;
3289 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003290
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003291 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003292
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003293 if (cursorRange.isInvalid())
3294 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003295
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003296 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3297
Ted Kremeneka333c662010-05-12 05:29:33 +00003298 // Adjust the annotated range based specific declarations.
3299 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3300 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003301 Decl *D = cxcursor::getCursorDecl(cursor);
3302 // Don't visit synthesized ObjC methods, since they have no syntatic
3303 // representation in the source.
3304 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3305 if (MD->isSynthesized())
3306 return CXChildVisit_Continue;
3307 }
3308 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003309 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3310 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003311 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003312 if (TLoc.isValid() &&
3313 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003314 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003315 }
3316 }
3317 }
3318
Ted Kremenek3f404602010-08-14 01:14:06 +00003319 // If the location of the cursor occurs within a macro instantiation, record
3320 // the spelling location of the cursor in our annotation map. We can then
3321 // paper over the token labelings during a post-processing step to try and
3322 // get cursor mappings for tokens that are the *arguments* of a macro
3323 // instantiation.
3324 if (L.isMacroID()) {
3325 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3326 // Only invalidate the old annotation if it isn't part of a preprocessing
3327 // directive. Here we assume that the default construction of CXCursor
3328 // results in CXCursor.kind being an initialized value (i.e., 0). If
3329 // this isn't the case, we can fix by doing lookup + insertion.
3330
3331 CXCursor &oldC = Annotated[rawEncoding];
3332 if (!clang_isPreprocessing(oldC.kind))
3333 oldC = cursor;
3334 }
3335
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003336 const enum CXCursorKind K = clang_getCursorKind(parent);
3337 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003338 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3339 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003340
3341 while (MoreTokens()) {
3342 const unsigned I = NextToken();
3343 SourceLocation TokLoc = GetTokenLoc(I);
3344 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3345 case RangeBefore:
3346 Cursors[I] = updateC;
3347 AdvanceToken();
3348 continue;
3349 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003350 case RangeOverlap:
3351 break;
3352 }
3353 break;
3354 }
3355
3356 // Visit children to get their cursor information.
3357 const unsigned BeforeChildren = NextToken();
3358 VisitChildren(cursor);
3359 const unsigned AfterChildren = NextToken();
3360
3361 // Adjust 'Last' to the last token within the extent of the cursor.
3362 while (MoreTokens()) {
3363 const unsigned I = NextToken();
3364 SourceLocation TokLoc = GetTokenLoc(I);
3365 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3366 case RangeBefore:
3367 assert(0 && "Infeasible");
3368 case RangeAfter:
3369 break;
3370 case RangeOverlap:
3371 Cursors[I] = updateC;
3372 AdvanceToken();
3373 continue;
3374 }
3375 break;
3376 }
3377 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003378
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003379 // Scan the tokens that are at the beginning of the cursor, but are not
3380 // capture by the child cursors.
3381
3382 // For AST elements within macros, rely on a post-annotate pass to
3383 // to correctly annotate the tokens with cursors. Otherwise we can
3384 // get confusing results of having tokens that map to cursors that really
3385 // are expanded by an instantiation.
3386 if (L.isMacroID())
3387 cursor = clang_getNullCursor();
3388
3389 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3390 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3391 break;
3392 Cursors[I] = cursor;
3393 }
3394 // Scan the tokens that are at the end of the cursor, but are not captured
3395 // but the child cursors.
3396 for (unsigned I = AfterChildren; I != Last; ++I)
3397 Cursors[I] = cursor;
3398
3399 TokIdx = Last;
3400 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003401}
3402
Ted Kremenek6db61092010-05-05 00:55:15 +00003403static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3404 CXCursor parent,
3405 CXClientData client_data) {
3406 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3407}
3408
3409extern "C" {
3410
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003411void clang_annotateTokens(CXTranslationUnit TU,
3412 CXToken *Tokens, unsigned NumTokens,
3413 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003414
3415 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003416 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003417
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003418 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003419 if (!CXXUnit) {
3420 // Any token we don't specifically annotate will have a NULL cursor.
3421 const CXCursor &C = clang_getNullCursor();
3422 for (unsigned I = 0; I != NumTokens; ++I)
3423 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003424 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003425 }
3426
Douglas Gregorbdf60622010-03-05 21:16:25 +00003427 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003428
Douglas Gregor0396f462010-03-19 05:22:59 +00003429 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003430 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003431 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3432 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003433 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3434 clang_getTokenLocation(TU,
3435 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003436
Douglas Gregor0396f462010-03-19 05:22:59 +00003437 // A mapping from the source locations found when re-lexing or traversing the
3438 // region of interest to the corresponding cursors.
3439 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003440
3441 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003442 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003443 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3444 std::pair<FileID, unsigned> BeginLocInfo
3445 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3446 std::pair<FileID, unsigned> EndLocInfo
3447 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003448
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003449 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003450 bool Invalid = false;
3451 if (BeginLocInfo.first == EndLocInfo.first &&
3452 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3453 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003454 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3455 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003456 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003457 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003458 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003459
3460 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003461 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003462 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003463 Token Tok;
3464 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003465
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003466 reprocess:
3467 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3468 // We have found a preprocessing directive. Gobble it up so that we
3469 // don't see it while preprocessing these tokens later, but keep track of
3470 // all of the token locations inside this preprocessing directive so that
3471 // we can annotate them appropriately.
3472 //
3473 // FIXME: Some simple tests here could identify macro definitions and
3474 // #undefs, to provide specific cursor kinds for those.
3475 std::vector<SourceLocation> Locations;
3476 do {
3477 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003478 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003479 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003480
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003481 using namespace cxcursor;
3482 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003483 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3484 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003485 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003486 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3487 Annotated[Locations[I].getRawEncoding()] = Cursor;
3488 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003489
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003490 if (Tok.isAtStartOfLine())
3491 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003492
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003493 continue;
3494 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003495
Douglas Gregor48072312010-03-18 15:23:44 +00003496 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003497 break;
3498 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003499 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003500
Douglas Gregor0396f462010-03-19 05:22:59 +00003501 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003502 // a specific cursor.
3503 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3504 CXXUnit, RegionOfInterest);
3505 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003506}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003507} // end: extern "C"
3508
3509//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003510// Operations for querying linkage of a cursor.
3511//===----------------------------------------------------------------------===//
3512
3513extern "C" {
3514CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003515 if (!clang_isDeclaration(cursor.kind))
3516 return CXLinkage_Invalid;
3517
Ted Kremenek16b42592010-03-03 06:36:57 +00003518 Decl *D = cxcursor::getCursorDecl(cursor);
3519 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3520 switch (ND->getLinkage()) {
3521 case NoLinkage: return CXLinkage_NoLinkage;
3522 case InternalLinkage: return CXLinkage_Internal;
3523 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3524 case ExternalLinkage: return CXLinkage_External;
3525 };
3526
3527 return CXLinkage_Invalid;
3528}
3529} // end: extern "C"
3530
3531//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003532// Operations for querying language of a cursor.
3533//===----------------------------------------------------------------------===//
3534
3535static CXLanguageKind getDeclLanguage(const Decl *D) {
3536 switch (D->getKind()) {
3537 default:
3538 break;
3539 case Decl::ImplicitParam:
3540 case Decl::ObjCAtDefsField:
3541 case Decl::ObjCCategory:
3542 case Decl::ObjCCategoryImpl:
3543 case Decl::ObjCClass:
3544 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003545 case Decl::ObjCForwardProtocol:
3546 case Decl::ObjCImplementation:
3547 case Decl::ObjCInterface:
3548 case Decl::ObjCIvar:
3549 case Decl::ObjCMethod:
3550 case Decl::ObjCProperty:
3551 case Decl::ObjCPropertyImpl:
3552 case Decl::ObjCProtocol:
3553 return CXLanguage_ObjC;
3554 case Decl::CXXConstructor:
3555 case Decl::CXXConversion:
3556 case Decl::CXXDestructor:
3557 case Decl::CXXMethod:
3558 case Decl::CXXRecord:
3559 case Decl::ClassTemplate:
3560 case Decl::ClassTemplatePartialSpecialization:
3561 case Decl::ClassTemplateSpecialization:
3562 case Decl::Friend:
3563 case Decl::FriendTemplate:
3564 case Decl::FunctionTemplate:
3565 case Decl::LinkageSpec:
3566 case Decl::Namespace:
3567 case Decl::NamespaceAlias:
3568 case Decl::NonTypeTemplateParm:
3569 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003570 case Decl::TemplateTemplateParm:
3571 case Decl::TemplateTypeParm:
3572 case Decl::UnresolvedUsingTypename:
3573 case Decl::UnresolvedUsingValue:
3574 case Decl::Using:
3575 case Decl::UsingDirective:
3576 case Decl::UsingShadow:
3577 return CXLanguage_CPlusPlus;
3578 }
3579
3580 return CXLanguage_C;
3581}
3582
3583extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003584
3585enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3586 if (clang_isDeclaration(cursor.kind))
3587 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3588 if (D->hasAttr<UnavailableAttr>() ||
3589 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3590 return CXAvailability_Available;
3591
3592 if (D->hasAttr<DeprecatedAttr>())
3593 return CXAvailability_Deprecated;
3594 }
3595
3596 return CXAvailability_Available;
3597}
3598
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003599CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3600 if (clang_isDeclaration(cursor.kind))
3601 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3602
3603 return CXLanguage_Invalid;
3604}
3605} // end: extern "C"
3606
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003607
3608//===----------------------------------------------------------------------===//
3609// C++ AST instrospection.
3610//===----------------------------------------------------------------------===//
3611
3612extern "C" {
3613unsigned clang_CXXMethod_isStatic(CXCursor C) {
3614 if (!clang_isDeclaration(C.kind))
3615 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003616
3617 CXXMethodDecl *Method = 0;
3618 Decl *D = cxcursor::getCursorDecl(C);
3619 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3620 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3621 else
3622 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3623 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003624}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003625
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003626} // end: extern "C"
3627
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003628//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003629// Attribute introspection.
3630//===----------------------------------------------------------------------===//
3631
3632extern "C" {
3633CXType clang_getIBOutletCollectionType(CXCursor C) {
3634 if (C.kind != CXCursor_IBOutletCollectionAttr)
3635 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3636
3637 IBOutletCollectionAttr *A =
3638 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3639
3640 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3641}
3642} // end: extern "C"
3643
3644//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003645// CXString Operations.
3646//===----------------------------------------------------------------------===//
3647
3648extern "C" {
3649const char *clang_getCString(CXString string) {
3650 return string.Spelling;
3651}
3652
3653void clang_disposeString(CXString string) {
3654 if (string.MustFreeString && string.Spelling)
3655 free((void*)string.Spelling);
3656}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003657
Ted Kremenekfb480492010-01-13 21:46:36 +00003658} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003659
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003660namespace clang { namespace cxstring {
3661CXString createCXString(const char *String, bool DupString){
3662 CXString Str;
3663 if (DupString) {
3664 Str.Spelling = strdup(String);
3665 Str.MustFreeString = 1;
3666 } else {
3667 Str.Spelling = String;
3668 Str.MustFreeString = 0;
3669 }
3670 return Str;
3671}
3672
3673CXString createCXString(llvm::StringRef String, bool DupString) {
3674 CXString Result;
3675 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3676 char *Spelling = (char *)malloc(String.size() + 1);
3677 memmove(Spelling, String.data(), String.size());
3678 Spelling[String.size()] = 0;
3679 Result.Spelling = Spelling;
3680 Result.MustFreeString = 1;
3681 } else {
3682 Result.Spelling = String.data();
3683 Result.MustFreeString = 0;
3684 }
3685 return Result;
3686}
3687}}
3688
Ted Kremenek04bb7162010-01-22 22:44:15 +00003689//===----------------------------------------------------------------------===//
3690// Misc. utility functions.
3691//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003692
Ted Kremenek04bb7162010-01-22 22:44:15 +00003693extern "C" {
3694
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003695CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003696 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003697}
3698
3699} // end: extern "C"