blob: 2b3364c77e186d266a1bb4d3e6088b233f0154dc [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);
Steve Naroff89922f82009-08-31 00:59:03 +0000388};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000389
Ted Kremenekab188932010-01-05 19:32:54 +0000390} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000391
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000392static SourceRange getRawCursorExtent(CXCursor C);
393
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000394RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000395 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
396}
397
Douglas Gregorb1373d02010-01-20 20:59:29 +0000398/// \brief Visit the given cursor and, if requested by the visitor,
399/// its children.
400///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000401/// \param Cursor the cursor to visit.
402///
403/// \param CheckRegionOfInterest if true, then the caller already checked that
404/// this cursor is within the region of interest.
405///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000406/// \returns true if the visitation should be aborted, false if it
407/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000408bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000409 if (clang_isInvalid(Cursor.kind))
410 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000411
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412 if (clang_isDeclaration(Cursor.kind)) {
413 Decl *D = getCursorDecl(Cursor);
414 assert(D && "Invalid declaration cursor");
415 if (D->getPCHLevel() > MaxPCHLevel)
416 return false;
417
418 if (D->isImplicit())
419 return false;
420 }
421
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000422 // If we have a range of interest, and this cursor doesn't intersect with it,
423 // we're done.
424 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000425 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000426 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000427 return false;
428 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000429
Douglas Gregorb1373d02010-01-20 20:59:29 +0000430 switch (Visitor(Cursor, Parent, ClientData)) {
431 case CXChildVisit_Break:
432 return true;
433
434 case CXChildVisit_Continue:
435 return false;
436
437 case CXChildVisit_Recurse:
438 return VisitChildren(Cursor);
439 }
440
Douglas Gregorfd643772010-01-25 16:45:46 +0000441 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000442}
443
Douglas Gregor788f5a12010-03-20 00:41:21 +0000444std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
445CursorVisitor::getPreprocessedEntities() {
446 PreprocessingRecord &PPRec
447 = *TU->getPreprocessor().getPreprocessingRecord();
448
449 bool OnlyLocalDecls
450 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
451
452 // There is no region of interest; we have to walk everything.
453 if (RegionOfInterest.isInvalid())
454 return std::make_pair(PPRec.begin(OnlyLocalDecls),
455 PPRec.end(OnlyLocalDecls));
456
457 // Find the file in which the region of interest lands.
458 SourceManager &SM = TU->getSourceManager();
459 std::pair<FileID, unsigned> Begin
460 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
461 std::pair<FileID, unsigned> End
462 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
463
464 // The region of interest spans files; we have to walk everything.
465 if (Begin.first != End.first)
466 return std::make_pair(PPRec.begin(OnlyLocalDecls),
467 PPRec.end(OnlyLocalDecls));
468
469 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
470 = TU->getPreprocessedEntitiesByFile();
471 if (ByFileMap.empty()) {
472 // Build the mapping from files to sets of preprocessed entities.
473 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
474 EEnd = PPRec.end(OnlyLocalDecls);
475 E != EEnd; ++E) {
476 std::pair<FileID, unsigned> P
477 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
478 ByFileMap[P.first].push_back(*E);
479 }
480 }
481
482 return std::make_pair(ByFileMap[Begin.first].begin(),
483 ByFileMap[Begin.first].end());
484}
485
Douglas Gregorb1373d02010-01-20 20:59:29 +0000486/// \brief Visit the children of the given cursor.
487///
488/// \returns true if the visitation should be aborted, false if it
489/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000490bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000491 if (clang_isReference(Cursor.kind)) {
492 // By definition, references have no children.
493 return false;
494 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000495
496 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000497 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000498 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000499
Douglas Gregorb1373d02010-01-20 20:59:29 +0000500 if (clang_isDeclaration(Cursor.kind)) {
501 Decl *D = getCursorDecl(Cursor);
502 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000503 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000504 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000505
Douglas Gregora59e3902010-01-21 23:27:09 +0000506 if (clang_isStatement(Cursor.kind))
507 return Visit(getCursorStmt(Cursor));
508 if (clang_isExpression(Cursor.kind))
509 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000510
Douglas Gregorb1373d02010-01-20 20:59:29 +0000511 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000512 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000513 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
514 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000515 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
516 TLEnd = CXXUnit->top_level_end();
517 TL != TLEnd; ++TL) {
518 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000519 return true;
520 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000521 } else if (VisitDeclContext(
522 CXXUnit->getASTContext().getTranslationUnitDecl()))
523 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000524
Douglas Gregor0396f462010-03-19 05:22:59 +0000525 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000526 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000527 // FIXME: Once we have the ability to deserialize a preprocessing record,
528 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000529 PreprocessingRecord::iterator E, EEnd;
530 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000531 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
532 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
533 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000534
Douglas Gregor0396f462010-03-19 05:22:59 +0000535 continue;
536 }
537
538 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
539 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
540 return true;
541
542 continue;
543 }
544 }
545 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000546 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000547 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000548
Douglas Gregorb1373d02010-01-20 20:59:29 +0000549 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000550 return false;
551}
552
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000553bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000554 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
555 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000556
Ted Kremenek664cffd2010-07-22 11:30:19 +0000557 if (Stmt *Body = B->getBody())
558 return Visit(MakeCXCursor(Body, StmtParent, TU));
559
560 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000561}
562
Douglas Gregorb1373d02010-01-20 20:59:29 +0000563bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000564 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000565 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000566
Ted Kremenek23173d72010-05-18 21:09:07 +0000567 Decl *D = *I;
568 if (D->getLexicalDeclContext() != DC)
569 continue;
570
571 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000572
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000573 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000574 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000575 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000576 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000577
578 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000579 case RangeBefore:
580 // This declaration comes before the region of interest; skip it.
581 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000582
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000583 case RangeAfter:
584 // This declaration comes after the region of interest; we're done.
585 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000586
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000587 case RangeOverlap:
588 // This declaration overlaps the region of interest; visit it.
589 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000590 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000591 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000592
Daniel Dunbard52864b2010-02-14 10:02:57 +0000593 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000594 return true;
595 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000596
Douglas Gregorb1373d02010-01-20 20:59:29 +0000597 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000598}
599
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000600bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
601 llvm_unreachable("Translation units are visited directly by Visit()");
602 return false;
603}
604
605bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
606 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
607 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000608
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000609 return false;
610}
611
612bool CursorVisitor::VisitTagDecl(TagDecl *D) {
613 return VisitDeclContext(D);
614}
615
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000616bool CursorVisitor::VisitClassTemplateSpecializationDecl(
617 ClassTemplateSpecializationDecl *D) {
618 bool ShouldVisitBody = false;
619 switch (D->getSpecializationKind()) {
620 case TSK_Undeclared:
621 case TSK_ImplicitInstantiation:
622 // Nothing to visit
623 return false;
624
625 case TSK_ExplicitInstantiationDeclaration:
626 case TSK_ExplicitInstantiationDefinition:
627 break;
628
629 case TSK_ExplicitSpecialization:
630 ShouldVisitBody = true;
631 break;
632 }
633
634 // Visit the template arguments used in the specialization.
635 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
636 TypeLoc TL = SpecType->getTypeLoc();
637 if (TemplateSpecializationTypeLoc *TSTLoc
638 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
639 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
640 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
641 return true;
642 }
643 }
644
645 if (ShouldVisitBody && VisitCXXRecordDecl(D))
646 return true;
647
648 return false;
649}
650
Douglas Gregor74dbe642010-08-31 19:31:58 +0000651bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
652 ClassTemplatePartialSpecializationDecl *D) {
653 // FIXME: Visit the "outer" template parameter lists on the TagDecl
654 // before visiting these template parameters.
655 if (VisitTemplateParameters(D->getTemplateParameters()))
656 return true;
657
658 // Visit the partial specialization arguments.
659 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
660 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
661 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
662 return true;
663
664 return VisitCXXRecordDecl(D);
665}
666
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000667bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000668 // Visit the default argument.
669 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
670 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
671 if (Visit(DefArg->getTypeLoc()))
672 return true;
673
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000674 return false;
675}
676
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000677bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
678 if (Expr *Init = D->getInitExpr())
679 return Visit(MakeCXCursor(Init, StmtParent, TU));
680 return false;
681}
682
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000683bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
684 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
685 if (Visit(TSInfo->getTypeLoc()))
686 return true;
687
688 return false;
689}
690
Douglas Gregorb1373d02010-01-20 20:59:29 +0000691bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000692 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
693 // Visit the function declaration's syntactic components in the order
694 // written. This requires a bit of work.
695 TypeLoc TL = TSInfo->getTypeLoc();
696 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
697
698 // If we have a function declared directly (without the use of a typedef),
699 // visit just the return type. Otherwise, just visit the function's type
700 // now.
701 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
702 (!FTL && Visit(TL)))
703 return true;
704
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000705 // Visit the nested-name-specifier, if present.
706 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
707 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
708 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000709
710 // Visit the declaration name.
711 if (VisitDeclarationNameInfo(ND->getNameInfo()))
712 return true;
713
714 // FIXME: Visit explicitly-specified template arguments!
715
716 // Visit the function parameters, if we have a function type.
717 if (FTL && VisitFunctionTypeLoc(*FTL, true))
718 return true;
719
720 // FIXME: Attributes?
721 }
722
Douglas Gregora59e3902010-01-21 23:27:09 +0000723 if (ND->isThisDeclarationADefinition() &&
724 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
725 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000726
Douglas Gregorb1373d02010-01-20 20:59:29 +0000727 return false;
728}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000729
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000730bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
731 if (VisitDeclaratorDecl(D))
732 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000733
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000734 if (Expr *BitWidth = D->getBitWidth())
735 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000736
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000737 return false;
738}
739
740bool CursorVisitor::VisitVarDecl(VarDecl *D) {
741 if (VisitDeclaratorDecl(D))
742 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000743
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000744 if (Expr *Init = D->getInit())
745 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000746
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000747 return false;
748}
749
Douglas Gregor84b51d72010-09-01 20:16:53 +0000750bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
751 if (VisitDeclaratorDecl(D))
752 return true;
753
754 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
755 if (Expr *DefArg = D->getDefaultArgument())
756 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
757
758 return false;
759}
760
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000761bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
762 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
763 // before visiting these template parameters.
764 if (VisitTemplateParameters(D->getTemplateParameters()))
765 return true;
766
767 return VisitFunctionDecl(D->getTemplatedDecl());
768}
769
Douglas Gregor39d6f072010-08-31 19:02:00 +0000770bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
771 // FIXME: Visit the "outer" template parameter lists on the TagDecl
772 // before visiting these template parameters.
773 if (VisitTemplateParameters(D->getTemplateParameters()))
774 return true;
775
776 return VisitCXXRecordDecl(D->getTemplatedDecl());
777}
778
Douglas Gregor84b51d72010-09-01 20:16:53 +0000779bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
780 if (VisitTemplateParameters(D->getTemplateParameters()))
781 return true;
782
783 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
784 VisitTemplateArgumentLoc(D->getDefaultArgument()))
785 return true;
786
787 return false;
788}
789
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000790bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000791 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
792 if (Visit(TSInfo->getTypeLoc()))
793 return true;
794
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000795 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000796 PEnd = ND->param_end();
797 P != PEnd; ++P) {
798 if (Visit(MakeCXCursor(*P, TU)))
799 return true;
800 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000801
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000802 if (ND->isThisDeclarationADefinition() &&
803 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
804 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000805
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000806 return false;
807}
808
Douglas Gregora59e3902010-01-21 23:27:09 +0000809bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
810 return VisitDeclContext(D);
811}
812
Douglas Gregorb1373d02010-01-20 20:59:29 +0000813bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000814 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
815 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000816 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000817
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000818 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
819 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
820 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000821 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000822 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000823
Douglas Gregora59e3902010-01-21 23:27:09 +0000824 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000825}
826
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000827bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
828 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
829 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
830 E = PID->protocol_end(); I != E; ++I, ++PL)
831 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
832 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000833
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000834 return VisitObjCContainerDecl(PID);
835}
836
Ted Kremenek23173d72010-05-18 21:09:07 +0000837bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000838 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
839 return true;
840
Ted Kremenek23173d72010-05-18 21:09:07 +0000841 // FIXME: This implements a workaround with @property declarations also being
842 // installed in the DeclContext for the @interface. Eventually this code
843 // should be removed.
844 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
845 if (!CDecl || !CDecl->IsClassExtension())
846 return false;
847
848 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
849 if (!ID)
850 return false;
851
852 IdentifierInfo *PropertyId = PD->getIdentifier();
853 ObjCPropertyDecl *prevDecl =
854 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
855
856 if (!prevDecl)
857 return false;
858
859 // Visit synthesized methods since they will be skipped when visiting
860 // the @interface.
861 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
862 if (MD->isSynthesized())
863 if (Visit(MakeCXCursor(MD, TU)))
864 return true;
865
866 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
867 if (MD->isSynthesized())
868 if (Visit(MakeCXCursor(MD, TU)))
869 return true;
870
871 return false;
872}
873
Douglas Gregorb1373d02010-01-20 20:59:29 +0000874bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000875 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000876 if (D->getSuperClass() &&
877 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000878 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000879 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000880 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000881
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000882 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
883 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
884 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000885 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000886 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000887
Douglas Gregora59e3902010-01-21 23:27:09 +0000888 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000889}
890
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000891bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
892 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000893}
894
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000895bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000896 // 'ID' could be null when dealing with invalid code.
897 if (ObjCInterfaceDecl *ID = D->getClassInterface())
898 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
899 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000900
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000901 return VisitObjCImplDecl(D);
902}
903
904bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
905#if 0
906 // Issue callbacks for super class.
907 // FIXME: No source location information!
908 if (D->getSuperClass() &&
909 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000910 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000911 TU)))
912 return true;
913#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000914
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000915 return VisitObjCImplDecl(D);
916}
917
918bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
919 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
920 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
921 E = D->protocol_end();
922 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000923 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000924 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000925
926 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000927}
928
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000929bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
930 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
931 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
932 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000933
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000934 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000935}
936
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000937bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
938 return VisitDeclContext(D);
939}
940
Douglas Gregor69319002010-08-31 23:48:11 +0000941bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000942 // Visit nested-name-specifier.
943 if (NestedNameSpecifier *Qualifier = D->getQualifier())
944 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
945 return true;
Douglas Gregor69319002010-08-31 23:48:11 +0000946
947 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
948 D->getTargetNameLoc(), TU));
949}
950
Douglas Gregor7e242562010-09-01 19:52:22 +0000951bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000952 // Visit nested-name-specifier.
953 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
954 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
955 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +0000956
957 // FIXME: Provide a multi-reference of some kind for all of the declarations
958 // that the using declaration refers to. We don't have this kind of cursor
959 // yet.
960
961 return VisitDeclarationNameInfo(D->getNameInfo());
962}
963
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000964bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000965 // Visit nested-name-specifier.
966 if (NestedNameSpecifier *Qualifier = D->getQualifier())
967 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
968 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000969
970 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
971 D->getIdentLocation(), TU));
972}
973
Douglas Gregor7e242562010-09-01 19:52:22 +0000974bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000975 // Visit nested-name-specifier.
976 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
977 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
978 return true;
979
Douglas Gregor7e242562010-09-01 19:52:22 +0000980 return VisitDeclarationNameInfo(D->getNameInfo());
981}
982
983bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
984 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000985 // Visit nested-name-specifier.
986 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
987 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
988 return true;
989
Douglas Gregor7e242562010-09-01 19:52:22 +0000990 return false;
991}
992
Douglas Gregor01829d32010-08-31 14:41:23 +0000993bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
994 switch (Name.getName().getNameKind()) {
995 case clang::DeclarationName::Identifier:
996 case clang::DeclarationName::CXXLiteralOperatorName:
997 case clang::DeclarationName::CXXOperatorName:
998 case clang::DeclarationName::CXXUsingDirective:
999 return false;
1000
1001 case clang::DeclarationName::CXXConstructorName:
1002 case clang::DeclarationName::CXXDestructorName:
1003 case clang::DeclarationName::CXXConversionFunctionName:
1004 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1005 return Visit(TSInfo->getTypeLoc());
1006 return false;
1007
1008 case clang::DeclarationName::ObjCZeroArgSelector:
1009 case clang::DeclarationName::ObjCOneArgSelector:
1010 case clang::DeclarationName::ObjCMultiArgSelector:
1011 // FIXME: Per-identifier location info?
1012 return false;
1013 }
1014
1015 return false;
1016}
1017
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001018bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1019 SourceRange Range) {
1020 // FIXME: This whole routine is a hack to work around the lack of proper
1021 // source information in nested-name-specifiers (PR5791). Since we do have
1022 // a beginning source location, we can visit the first component of the
1023 // nested-name-specifier, if it's a single-token component.
1024 if (!NNS)
1025 return false;
1026
1027 // Get the first component in the nested-name-specifier.
1028 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1029 NNS = Prefix;
1030
1031 switch (NNS->getKind()) {
1032 case NestedNameSpecifier::Namespace:
1033 // FIXME: The token at this source location might actually have been a
1034 // namespace alias, but we don't model that. Lame!
1035 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1036 TU));
1037
1038 case NestedNameSpecifier::TypeSpec: {
1039 // If the type has a form where we know that the beginning of the source
1040 // range matches up with a reference cursor. Visit the appropriate reference
1041 // cursor.
1042 Type *T = NNS->getAsType();
1043 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1044 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1045 if (const TagType *Tag = dyn_cast<TagType>(T))
1046 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1047 if (const TemplateSpecializationType *TST
1048 = dyn_cast<TemplateSpecializationType>(T))
1049 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1050 break;
1051 }
1052
1053 case NestedNameSpecifier::TypeSpecWithTemplate:
1054 case NestedNameSpecifier::Global:
1055 case NestedNameSpecifier::Identifier:
1056 break;
1057 }
1058
1059 return false;
1060}
1061
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001062bool CursorVisitor::VisitTemplateParameters(
1063 const TemplateParameterList *Params) {
1064 if (!Params)
1065 return false;
1066
1067 for (TemplateParameterList::const_iterator P = Params->begin(),
1068 PEnd = Params->end();
1069 P != PEnd; ++P) {
1070 if (Visit(MakeCXCursor(*P, TU)))
1071 return true;
1072 }
1073
1074 return false;
1075}
1076
Douglas Gregor0b36e612010-08-31 20:37:03 +00001077bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1078 switch (Name.getKind()) {
1079 case TemplateName::Template:
1080 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1081
1082 case TemplateName::OverloadedTemplate:
1083 // FIXME: We need a way to return multiple lookup results in a single
1084 // cursor.
1085 return false;
1086
1087 case TemplateName::DependentTemplate:
1088 // FIXME: Visit nested-name-specifier.
1089 return false;
1090
1091 case TemplateName::QualifiedTemplate:
1092 // FIXME: Visit nested-name-specifier.
1093 return Visit(MakeCursorTemplateRef(
1094 Name.getAsQualifiedTemplateName()->getDecl(),
1095 Loc, TU));
1096 }
1097
1098 return false;
1099}
1100
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001101bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1102 switch (TAL.getArgument().getKind()) {
1103 case TemplateArgument::Null:
1104 case TemplateArgument::Integral:
1105 return false;
1106
1107 case TemplateArgument::Pack:
1108 // FIXME: Implement when variadic templates come along.
1109 return false;
1110
1111 case TemplateArgument::Type:
1112 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1113 return Visit(TSInfo->getTypeLoc());
1114 return false;
1115
1116 case TemplateArgument::Declaration:
1117 if (Expr *E = TAL.getSourceDeclExpression())
1118 return Visit(MakeCXCursor(E, StmtParent, TU));
1119 return false;
1120
1121 case TemplateArgument::Expression:
1122 if (Expr *E = TAL.getSourceExpression())
1123 return Visit(MakeCXCursor(E, StmtParent, TU));
1124 return false;
1125
1126 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001127 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1128 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001129 }
1130
1131 return false;
1132}
1133
Ted Kremeneka0536d82010-05-07 01:04:29 +00001134bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1135 return VisitDeclContext(D);
1136}
1137
Douglas Gregor01829d32010-08-31 14:41:23 +00001138bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1139 return Visit(TL.getUnqualifiedLoc());
1140}
1141
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001142bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1143 ASTContext &Context = TU->getASTContext();
1144
1145 // Some builtin types (such as Objective-C's "id", "sel", and
1146 // "Class") have associated declarations. Create cursors for those.
1147 QualType VisitType;
1148 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001149 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001150 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001151 case BuiltinType::Char_U:
1152 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001153 case BuiltinType::Char16:
1154 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001155 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001156 case BuiltinType::UInt:
1157 case BuiltinType::ULong:
1158 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001159 case BuiltinType::UInt128:
1160 case BuiltinType::Char_S:
1161 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001162 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001163 case BuiltinType::Short:
1164 case BuiltinType::Int:
1165 case BuiltinType::Long:
1166 case BuiltinType::LongLong:
1167 case BuiltinType::Int128:
1168 case BuiltinType::Float:
1169 case BuiltinType::Double:
1170 case BuiltinType::LongDouble:
1171 case BuiltinType::NullPtr:
1172 case BuiltinType::Overload:
1173 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001174 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001175
1176 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001177 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001178
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001179 case BuiltinType::ObjCId:
1180 VisitType = Context.getObjCIdType();
1181 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001182
1183 case BuiltinType::ObjCClass:
1184 VisitType = Context.getObjCClassType();
1185 break;
1186
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001187 case BuiltinType::ObjCSel:
1188 VisitType = Context.getObjCSelType();
1189 break;
1190 }
1191
1192 if (!VisitType.isNull()) {
1193 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001194 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001195 TU));
1196 }
1197
1198 return false;
1199}
1200
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001201bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1202 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1203}
1204
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001205bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1206 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1207}
1208
1209bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1210 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1211}
1212
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001213bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1214 // FIXME: We can't visit the template template parameter, but there's
1215 // no context information with which we can match up the depth/index in the
1216 // type to the appropriate
1217 return false;
1218}
1219
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001220bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1221 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1222 return true;
1223
John McCallc12c5bb2010-05-15 11:32:37 +00001224 return false;
1225}
1226
1227bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1228 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1229 return true;
1230
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001231 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1232 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1233 TU)))
1234 return true;
1235 }
1236
1237 return false;
1238}
1239
1240bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001241 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001242}
1243
1244bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1245 return Visit(TL.getPointeeLoc());
1246}
1247
1248bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1249 return Visit(TL.getPointeeLoc());
1250}
1251
1252bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1253 return Visit(TL.getPointeeLoc());
1254}
1255
1256bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001257 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001258}
1259
1260bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001261 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001262}
1263
Douglas Gregor01829d32010-08-31 14:41:23 +00001264bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1265 bool SkipResultType) {
1266 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001267 return true;
1268
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001269 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001270 if (Decl *D = TL.getArg(I))
1271 if (Visit(MakeCXCursor(D, TU)))
1272 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001273
1274 return false;
1275}
1276
1277bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1278 if (Visit(TL.getElementLoc()))
1279 return true;
1280
1281 if (Expr *Size = TL.getSizeExpr())
1282 return Visit(MakeCXCursor(Size, StmtParent, TU));
1283
1284 return false;
1285}
1286
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001287bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1288 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001289 // Visit the template name.
1290 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1291 TL.getTemplateNameLoc()))
1292 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001293
1294 // Visit the template arguments.
1295 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1296 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1297 return true;
1298
1299 return false;
1300}
1301
Douglas Gregor2332c112010-01-21 20:48:56 +00001302bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1303 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1304}
1305
1306bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1307 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1308 return Visit(TSInfo->getTypeLoc());
1309
1310 return false;
1311}
1312
Douglas Gregora59e3902010-01-21 23:27:09 +00001313bool CursorVisitor::VisitStmt(Stmt *S) {
1314 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1315 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001316 if (Stmt *C = *Child)
1317 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1318 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001319 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001320
Douglas Gregora59e3902010-01-21 23:27:09 +00001321 return false;
1322}
1323
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001324bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1325 // Specially handle CaseStmts because they can be nested, e.g.:
1326 //
1327 // case 1:
1328 // case 2:
1329 //
1330 // In this case the second CaseStmt is the child of the first. Walking
1331 // these recursively can blow out the stack.
1332 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1333 while (true) {
1334 // Set the Parent field to Cursor, then back to its old value once we're
1335 // done.
1336 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1337
1338 if (Stmt *LHS = S->getLHS())
1339 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1340 return true;
1341 if (Stmt *RHS = S->getRHS())
1342 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1343 return true;
1344 if (Stmt *SubStmt = S->getSubStmt()) {
1345 if (!isa<CaseStmt>(SubStmt))
1346 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1347
1348 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1349 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1350 Cursor = MakeCXCursor(CS, StmtParent, TU);
1351 if (RegionOfInterest.isValid()) {
1352 SourceRange Range = CS->getSourceRange();
1353 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1354 return false;
1355 }
1356
1357 switch (Visitor(Cursor, Parent, ClientData)) {
1358 case CXChildVisit_Break: return true;
1359 case CXChildVisit_Continue: return false;
1360 case CXChildVisit_Recurse:
1361 // Perform tail-recursion manually.
1362 S = CS;
1363 continue;
1364 }
1365 }
1366 return false;
1367 }
1368}
1369
Douglas Gregora59e3902010-01-21 23:27:09 +00001370bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1371 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1372 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001373 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001374 return true;
1375 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001376
Douglas Gregora59e3902010-01-21 23:27:09 +00001377 return false;
1378}
1379
Douglas Gregorf5bab412010-01-22 01:00:11 +00001380bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1381 if (VarDecl *Var = S->getConditionVariable()) {
1382 if (Visit(MakeCXCursor(Var, TU)))
1383 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001384 }
1385
Douglas Gregor263b47b2010-01-25 16:12:32 +00001386 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1387 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001388 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1389 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001390 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1391 return true;
1392
1393 return false;
1394}
1395
1396bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1397 if (VarDecl *Var = S->getConditionVariable()) {
1398 if (Visit(MakeCXCursor(Var, TU)))
1399 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001400 }
1401
Douglas Gregor263b47b2010-01-25 16:12:32 +00001402 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1403 return true;
1404 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1405 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001406
Douglas Gregor263b47b2010-01-25 16:12:32 +00001407 return false;
1408}
1409
1410bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1411 if (VarDecl *Var = S->getConditionVariable()) {
1412 if (Visit(MakeCXCursor(Var, TU)))
1413 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001414 }
1415
Douglas Gregor263b47b2010-01-25 16:12:32 +00001416 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1417 return true;
1418 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001419 return true;
1420
Douglas Gregor263b47b2010-01-25 16:12:32 +00001421 return false;
1422}
1423
1424bool CursorVisitor::VisitForStmt(ForStmt *S) {
1425 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1426 return true;
1427 if (VarDecl *Var = S->getConditionVariable()) {
1428 if (Visit(MakeCXCursor(Var, TU)))
1429 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001430 }
1431
Douglas Gregor263b47b2010-01-25 16:12:32 +00001432 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1433 return true;
1434 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1435 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001436 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1437 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001438
Douglas Gregorf5bab412010-01-22 01:00:11 +00001439 return false;
1440}
1441
Douglas Gregor8947a752010-09-02 20:35:02 +00001442bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1443 // Visit nested-name-specifier, if present.
1444 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1445 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1446 return true;
1447
1448 // Visit declaration name.
1449 if (VisitDeclarationNameInfo(E->getNameInfo()))
1450 return true;
1451
1452 // Visit explicitly-specified template arguments.
1453 if (E->hasExplicitTemplateArgs()) {
1454 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1455 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1456 *ArgEnd = Arg + Args.NumTemplateArgs;
1457 Arg != ArgEnd; ++Arg)
1458 if (VisitTemplateArgumentLoc(*Arg))
1459 return true;
1460 }
1461
1462 return false;
1463}
1464
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001465bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1466 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1467 return true;
1468
1469 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1470 return true;
1471
1472 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1473 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1474 return true;
1475
1476 return false;
1477}
1478
Ted Kremenek3064ef92010-08-27 21:34:58 +00001479bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1480 if (D->isDefinition()) {
1481 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1482 E = D->bases_end(); I != E; ++I) {
1483 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1484 return true;
1485 }
1486 }
1487
1488 return VisitTagDecl(D);
1489}
1490
1491
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001492bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1493 return Visit(B->getBlockDecl());
1494}
1495
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001496bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1497 // FIXME: Visit fields as well?
1498 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1499 return true;
1500
1501 return VisitExpr(E);
1502}
1503
Douglas Gregor336fd812010-01-23 00:40:08 +00001504bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1505 if (E->isArgumentType()) {
1506 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1507 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001508
Douglas Gregor336fd812010-01-23 00:40:08 +00001509 return false;
1510 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001511
Douglas Gregor336fd812010-01-23 00:40:08 +00001512 return VisitExpr(E);
1513}
1514
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001515bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1516 // Visit the base expression.
1517 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1518 return true;
1519
1520 // Visit the nested-name-specifier
1521 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1522 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1523 return true;
1524
1525 // Visit the declaration name.
1526 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1527 return true;
1528
1529 // Visit the explicitly-specified template arguments, if any.
1530 if (E->hasExplicitTemplateArgs()) {
1531 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1532 *ArgEnd = Arg + E->getNumTemplateArgs();
1533 Arg != ArgEnd;
1534 ++Arg) {
1535 if (VisitTemplateArgumentLoc(*Arg))
1536 return true;
1537 }
1538 }
1539
1540 return false;
1541}
1542
Douglas Gregor336fd812010-01-23 00:40:08 +00001543bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1544 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1545 if (Visit(TSInfo->getTypeLoc()))
1546 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001547
Douglas Gregor336fd812010-01-23 00:40:08 +00001548 return VisitCastExpr(E);
1549}
1550
1551bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1552 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1553 if (Visit(TSInfo->getTypeLoc()))
1554 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001555
Douglas Gregor336fd812010-01-23 00:40:08 +00001556 return VisitExpr(E);
1557}
1558
Douglas Gregor648220e2010-08-10 15:02:34 +00001559bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1560 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1561 Visit(E->getArgTInfo2()->getTypeLoc());
1562}
1563
1564bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1565 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1566 return true;
1567
1568 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1569}
1570
Douglas Gregor94802292010-09-02 21:20:16 +00001571bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1572 if (E->isTypeOperand()) {
1573 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1574 return Visit(TSInfo->getTypeLoc());
1575
1576 return false;
1577 }
1578
1579 return VisitExpr(E);
1580}
1581
Douglas Gregorc2350e52010-03-08 16:40:19 +00001582bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001583 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1584 if (Visit(TSInfo->getTypeLoc()))
1585 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001586
1587 return VisitExpr(E);
1588}
1589
Douglas Gregor81d34662010-04-20 15:39:42 +00001590bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1591 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1592}
1593
1594
Ted Kremenek09dfa372010-02-18 05:46:33 +00001595bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001596 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1597 i != e; ++i)
1598 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001599 return true;
1600
1601 return false;
1602}
1603
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001604extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001605CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1606 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001607 // We use crash recovery to make some of our APIs more reliable, implicitly
1608 // enable it.
1609 llvm::CrashRecoveryContext::Enable();
1610
Douglas Gregora030b7c2010-01-22 20:35:53 +00001611 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001612 if (excludeDeclarationsFromPCH)
1613 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001614 if (displayDiagnostics)
1615 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001616 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001617}
1618
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001619void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001620 if (CIdx)
1621 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001622 if (getenv("LIBCLANG_TIMING"))
1623 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001624}
1625
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001626void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001627 if (CIdx) {
1628 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1629 CXXIdx->setUseExternalASTGeneration(value);
1630 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001631}
1632
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001633CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001634 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001635 if (!CIdx)
1636 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001637
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001638 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001639
Douglas Gregor28019772010-04-05 23:52:57 +00001640 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001641 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001642 CXXIdx->getOnlyLocalDecls(),
1643 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001644}
1645
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001646unsigned clang_defaultEditingTranslationUnitOptions() {
1647 return CXTranslationUnit_PrecompiledPreamble;
1648}
1649
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001650CXTranslationUnit
1651clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1652 const char *source_filename,
1653 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001654 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001655 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001656 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001657 return clang_parseTranslationUnit(CIdx, source_filename,
1658 command_line_args, num_command_line_args,
1659 unsaved_files, num_unsaved_files,
1660 CXTranslationUnit_DetailedPreprocessingRecord);
1661}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001662
1663struct ParseTranslationUnitInfo {
1664 CXIndex CIdx;
1665 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001666 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001667 int num_command_line_args;
1668 struct CXUnsavedFile *unsaved_files;
1669 unsigned num_unsaved_files;
1670 unsigned options;
1671 CXTranslationUnit result;
1672};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001673static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001674 ParseTranslationUnitInfo *PTUI =
1675 static_cast<ParseTranslationUnitInfo*>(UserData);
1676 CXIndex CIdx = PTUI->CIdx;
1677 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001678 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001679 int num_command_line_args = PTUI->num_command_line_args;
1680 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1681 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1682 unsigned options = PTUI->options;
1683 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001684
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001685 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001686 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001687
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001688 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1689
Douglas Gregor44c181a2010-07-23 00:33:23 +00001690 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001691 bool CompleteTranslationUnit
1692 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001693 bool CacheCodeCompetionResults
1694 = options & CXTranslationUnit_CacheCompletionResults;
1695
Douglas Gregor5352ac02010-01-28 00:27:43 +00001696 // Configure the diagnostics.
1697 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001698 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1699 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001700
Douglas Gregor4db64a42010-01-23 00:14:00 +00001701 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1702 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001703 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001704 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001705 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001706 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1707 Buffer));
1708 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001709
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001710 if (!CXXIdx->getUseExternalASTGeneration()) {
1711 llvm::SmallVector<const char *, 16> Args;
1712
1713 // The 'source_filename' argument is optional. If the caller does not
1714 // specify it then it is assumed that the source file is specified
1715 // in the actual argument list.
1716 if (source_filename)
1717 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001718
1719 // Since the Clang C library is primarily used by batch tools dealing with
1720 // (often very broken) source code, where spell-checking can have a
1721 // significant negative impact on performance (particularly when
1722 // precompiled headers are involved), we disable it by default.
1723 // Note that we place this argument early in the list, so that it can be
1724 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001725 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001726
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001727 Args.insert(Args.end(), command_line_args,
1728 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001729
Douglas Gregor44c181a2010-07-23 00:33:23 +00001730 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001731 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1732 Args.push_back("-Xclang");
1733 Args.push_back("-detailed-preprocessing-record");
1734 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001735
Douglas Gregor5352ac02010-01-28 00:27:43 +00001736 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001737
Ted Kremenek29b72842010-01-07 22:49:05 +00001738#ifdef USE_CRASHTRACER
1739 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001740#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001741
Daniel Dunbar94220972009-12-05 02:17:18 +00001742 llvm::OwningPtr<ASTUnit> Unit(
1743 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001744 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001745 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001746 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001747 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001748 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001749 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001750 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001751 CompleteTranslationUnit,
1752 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001753
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001754 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001755 // Make sure to check that 'Unit' is non-NULL.
1756 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001757 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1758 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001759 D != DEnd; ++D) {
1760 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001761 CXString Msg = clang_formatDiagnostic(&Diag,
1762 clang_defaultDiagnosticDisplayOptions());
1763 fprintf(stderr, "%s\n", clang_getCString(Msg));
1764 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001765 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001766#ifdef LLVM_ON_WIN32
1767 // On Windows, force a flush, since there may be multiple copies of
1768 // stderr and stdout in the file system, all with different buffers
1769 // but writing to the same device.
1770 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001771#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001772 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001773 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001774
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001775 PTUI->result = Unit.take();
1776 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001777 }
1778
Ted Kremenek139ba862009-10-22 00:03:57 +00001779 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001780 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001781
Ted Kremenek139ba862009-10-22 00:03:57 +00001782 // First add the complete path to the 'clang' executable.
1783 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001784 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001785
Ted Kremenek139ba862009-10-22 00:03:57 +00001786 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001787 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001788
Ted Kremenek139ba862009-10-22 00:03:57 +00001789 // The 'source_filename' argument is optional. If the caller does not
1790 // specify it then it is assumed that the source file is specified
1791 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001792 if (source_filename)
1793 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001794
Steve Naroff37b5ac22009-10-15 20:50:09 +00001795 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001796 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001797 char astTmpFile[L_tmpnam];
1798 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001799
1800 // Since the Clang C library is primarily used by batch tools dealing with
1801 // (often very broken) source code, where spell-checking can have a
1802 // significant negative impact on performance (particularly when
1803 // precompiled headers are involved), we disable it by default.
1804 // Note that we place this argument early in the list, so that it can be
1805 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001806 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001807
Douglas Gregor4db64a42010-01-23 00:14:00 +00001808 // Remap any unsaved files to temporary files.
1809 std::vector<llvm::sys::Path> TemporaryFiles;
1810 std::vector<std::string> RemapArgs;
1811 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001812 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001813
Douglas Gregor4db64a42010-01-23 00:14:00 +00001814 // The pointers into the elements of RemapArgs are stable because we
1815 // won't be adding anything to RemapArgs after this point.
1816 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1817 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001818
Ted Kremenek139ba862009-10-22 00:03:57 +00001819 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1820 for (int i = 0; i < num_command_line_args; ++i)
1821 if (const char *arg = command_line_args[i]) {
1822 if (strcmp(arg, "-o") == 0) {
1823 ++i; // Also skip the matching argument.
1824 continue;
1825 }
1826 if (strcmp(arg, "-emit-ast") == 0 ||
1827 strcmp(arg, "-c") == 0 ||
1828 strcmp(arg, "-fsyntax-only") == 0) {
1829 continue;
1830 }
1831
1832 // Keep the argument.
1833 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001834 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001835
Douglas Gregord93256e2010-01-28 06:00:51 +00001836 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001837 char tmpFileResults[L_tmpnam];
1838 char *tmpResultsFileName = tmpnam(tmpFileResults);
1839 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001840 TemporaryFiles.push_back(DiagnosticsFile);
1841 argv.push_back("-fdiagnostics-binary");
1842
Douglas Gregor44c181a2010-07-23 00:33:23 +00001843 // Do we need the detailed preprocessing record?
1844 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1845 argv.push_back("-Xclang");
1846 argv.push_back("-detailed-preprocessing-record");
1847 }
1848
Ted Kremenek139ba862009-10-22 00:03:57 +00001849 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001850 argv.push_back(NULL);
1851
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001852 // Invoke 'clang'.
1853 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1854 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001855 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001856 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1857 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001858 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001859 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001860 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001861
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001862 if (!ErrMsg.empty()) {
1863 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001864 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001865 I != E; ++I) {
1866 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001867 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001868 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001869 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001870
Daniel Dunbar32141c82010-02-23 20:23:45 +00001871 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001872 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001873
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001874 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001875 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001876 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001877 RemappedFiles.size(),
1878 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001879 if (ATU) {
1880 LoadSerializedDiagnostics(DiagnosticsFile,
1881 num_unsaved_files, unsaved_files,
1882 ATU->getFileManager(),
1883 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001884 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001885 } else if (CXXIdx->getDisplayDiagnostics()) {
1886 // We failed to load the ASTUnit, but we can still deserialize the
1887 // diagnostics and emit them.
1888 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001889 Diagnostic Diag;
1890 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001891 // FIXME: Faked LangOpts!
1892 LangOptions LangOpts;
1893 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1894 LoadSerializedDiagnostics(DiagnosticsFile,
1895 num_unsaved_files, unsaved_files,
1896 FileMgr, SourceMgr, Diags);
1897 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1898 DEnd = Diags.end();
1899 D != DEnd; ++D) {
1900 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001901 CXString Msg = clang_formatDiagnostic(&Diag,
1902 clang_defaultDiagnosticDisplayOptions());
1903 fprintf(stderr, "%s\n", clang_getCString(Msg));
1904 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001905 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001906
1907#ifdef LLVM_ON_WIN32
1908 // On Windows, force a flush, since there may be multiple copies of
1909 // stderr and stdout in the file system, all with different buffers
1910 // but writing to the same device.
1911 fflush(stderr);
1912#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001913 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001914
Douglas Gregor313e26c2010-02-18 23:35:40 +00001915 if (ATU) {
1916 // Make the translation unit responsible for destroying all temporary files.
1917 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1918 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001919 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001920 } else {
1921 // Destroy all of the temporary files now; they can't be referenced any
1922 // longer.
1923 llvm::sys::Path(astTmpFile).eraseFromDisk();
1924 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1925 TemporaryFiles[i].eraseFromDisk();
1926 }
1927
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001928 PTUI->result = ATU;
1929}
1930CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1931 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001932 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001933 int num_command_line_args,
1934 struct CXUnsavedFile *unsaved_files,
1935 unsigned num_unsaved_files,
1936 unsigned options) {
1937 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1938 num_command_line_args, unsaved_files, num_unsaved_files,
1939 options, 0 };
1940 llvm::CrashRecoveryContext CRC;
1941
1942 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001943 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1944 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1945 fprintf(stderr, " 'command_line_args' : [");
1946 for (int i = 0; i != num_command_line_args; ++i) {
1947 if (i)
1948 fprintf(stderr, ", ");
1949 fprintf(stderr, "'%s'", command_line_args[i]);
1950 }
1951 fprintf(stderr, "],\n");
1952 fprintf(stderr, " 'unsaved_files' : [");
1953 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1954 if (i)
1955 fprintf(stderr, ", ");
1956 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1957 unsaved_files[i].Length);
1958 }
1959 fprintf(stderr, "],\n");
1960 fprintf(stderr, " 'options' : %d,\n", options);
1961 fprintf(stderr, "}\n");
1962
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001963 return 0;
1964 }
1965
1966 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001967}
1968
Douglas Gregor19998442010-08-13 15:35:05 +00001969unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1970 return CXSaveTranslationUnit_None;
1971}
1972
1973int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1974 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001975 if (!TU)
1976 return 1;
1977
1978 return static_cast<ASTUnit *>(TU)->Save(FileName);
1979}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001980
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001981void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001982 if (CTUnit) {
1983 // If the translation unit has been marked as unsafe to free, just discard
1984 // it.
1985 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1986 return;
1987
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001988 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001989 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001990}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001991
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001992unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1993 return CXReparse_None;
1994}
1995
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001996struct ReparseTranslationUnitInfo {
1997 CXTranslationUnit TU;
1998 unsigned num_unsaved_files;
1999 struct CXUnsavedFile *unsaved_files;
2000 unsigned options;
2001 int result;
2002};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002003static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002004 ReparseTranslationUnitInfo *RTUI =
2005 static_cast<ReparseTranslationUnitInfo*>(UserData);
2006 CXTranslationUnit TU = RTUI->TU;
2007 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2008 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2009 unsigned options = RTUI->options;
2010 (void) options;
2011 RTUI->result = 1;
2012
Douglas Gregorabc563f2010-07-19 21:46:24 +00002013 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002014 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002015
2016 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2017 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2018 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2019 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002020 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002021 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2022 Buffer));
2023 }
2024
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002025 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
2026 RemappedFiles.size()))
2027 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002028}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002029int clang_reparseTranslationUnit(CXTranslationUnit TU,
2030 unsigned num_unsaved_files,
2031 struct CXUnsavedFile *unsaved_files,
2032 unsigned options) {
2033 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2034 options, 0 };
2035 llvm::CrashRecoveryContext CRC;
2036
2037 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002038 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002039 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2040 return 1;
2041 }
2042
2043 return RTUI.result;
2044}
2045
Douglas Gregordf95a132010-08-09 20:45:32 +00002046
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002047CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002048 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002049 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002050
Steve Naroff77accc12009-09-03 18:19:54 +00002051 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002052 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002053}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002054
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002055CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002056 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002057 return Result;
2058}
2059
Ted Kremenekfb480492010-01-13 21:46:36 +00002060} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002061
Ted Kremenekfb480492010-01-13 21:46:36 +00002062//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002063// CXSourceLocation and CXSourceRange Operations.
2064//===----------------------------------------------------------------------===//
2065
Douglas Gregorb9790342010-01-22 21:44:22 +00002066extern "C" {
2067CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002068 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002069 return Result;
2070}
2071
2072unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002073 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2074 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2075 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002076}
2077
2078CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2079 CXFile file,
2080 unsigned line,
2081 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002082 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002083 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002084
Douglas Gregorb9790342010-01-22 21:44:22 +00002085 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2086 SourceLocation SLoc
2087 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002088 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002089 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002090
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002091 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002092}
2093
Douglas Gregor5352ac02010-01-28 00:27:43 +00002094CXSourceRange clang_getNullRange() {
2095 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2096 return Result;
2097}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002098
Douglas Gregor5352ac02010-01-28 00:27:43 +00002099CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2100 if (begin.ptr_data[0] != end.ptr_data[0] ||
2101 begin.ptr_data[1] != end.ptr_data[1])
2102 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002103
2104 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002105 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002106 return Result;
2107}
2108
Douglas Gregor46766dc2010-01-26 19:19:08 +00002109void clang_getInstantiationLocation(CXSourceLocation location,
2110 CXFile *file,
2111 unsigned *line,
2112 unsigned *column,
2113 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002114 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2115
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002116 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002117 if (file)
2118 *file = 0;
2119 if (line)
2120 *line = 0;
2121 if (column)
2122 *column = 0;
2123 if (offset)
2124 *offset = 0;
2125 return;
2126 }
2127
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002128 const SourceManager &SM =
2129 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002130 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002131
2132 if (file)
2133 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2134 if (line)
2135 *line = SM.getInstantiationLineNumber(InstLoc);
2136 if (column)
2137 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002138 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002139 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002140}
2141
Douglas Gregor1db19de2010-01-19 21:36:55 +00002142CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002143 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002144 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002145 return Result;
2146}
2147
2148CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002149 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002150 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002151 return Result;
2152}
2153
Douglas Gregorb9790342010-01-22 21:44:22 +00002154} // end: extern "C"
2155
Douglas Gregor1db19de2010-01-19 21:36:55 +00002156//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002157// CXFile Operations.
2158//===----------------------------------------------------------------------===//
2159
2160extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002161CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002162 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002163 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002164
Steve Naroff88145032009-10-27 14:35:18 +00002165 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002166 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002167}
2168
2169time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002170 if (!SFile)
2171 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002172
Steve Naroff88145032009-10-27 14:35:18 +00002173 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2174 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002175}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002176
Douglas Gregorb9790342010-01-22 21:44:22 +00002177CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2178 if (!tu)
2179 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002180
Douglas Gregorb9790342010-01-22 21:44:22 +00002181 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002182
Douglas Gregorb9790342010-01-22 21:44:22 +00002183 FileManager &FMgr = CXXUnit->getFileManager();
2184 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2185 return const_cast<FileEntry *>(File);
2186}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002187
Ted Kremenekfb480492010-01-13 21:46:36 +00002188} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002189
Ted Kremenekfb480492010-01-13 21:46:36 +00002190//===----------------------------------------------------------------------===//
2191// CXCursor Operations.
2192//===----------------------------------------------------------------------===//
2193
Ted Kremenekfb480492010-01-13 21:46:36 +00002194static Decl *getDeclFromExpr(Stmt *E) {
2195 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2196 return RefExpr->getDecl();
2197 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2198 return ME->getMemberDecl();
2199 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2200 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002201
Ted Kremenekfb480492010-01-13 21:46:36 +00002202 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2203 return getDeclFromExpr(CE->getCallee());
2204 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2205 return getDeclFromExpr(CE->getSubExpr());
2206 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2207 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002208
Ted Kremenekfb480492010-01-13 21:46:36 +00002209 return 0;
2210}
2211
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002212static SourceLocation getLocationFromExpr(Expr *E) {
2213 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2214 return /*FIXME:*/Msg->getLeftLoc();
2215 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2216 return DRE->getLocation();
2217 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2218 return Member->getMemberLoc();
2219 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2220 return Ivar->getLocation();
2221 return E->getLocStart();
2222}
2223
Ted Kremenekfb480492010-01-13 21:46:36 +00002224extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002225
2226unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002227 CXCursorVisitor visitor,
2228 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002229 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002230
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002231 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2232 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002233 return CursorVis.VisitChildren(parent);
2234}
2235
Douglas Gregor78205d42010-01-20 21:45:58 +00002236static CXString getDeclSpelling(Decl *D) {
2237 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2238 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002239 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002240
Douglas Gregor78205d42010-01-20 21:45:58 +00002241 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002242 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002243
Douglas Gregor78205d42010-01-20 21:45:58 +00002244 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2245 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2246 // and returns different names. NamedDecl returns the class name and
2247 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002248 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002249
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002250 if (isa<UsingDirectiveDecl>(D))
2251 return createCXString("");
2252
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002253 llvm::SmallString<1024> S;
2254 llvm::raw_svector_ostream os(S);
2255 ND->printName(os);
2256
2257 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002258}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002259
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002260CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002261 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002262 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002263
Steve Narofff334b4e2009-09-02 18:26:48 +00002264 if (clang_isReference(C.kind)) {
2265 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002266 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002267 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002268 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002269 }
2270 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002271 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002272 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002273 }
2274 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002275 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002276 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002277 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002278 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002279 case CXCursor_CXXBaseSpecifier: {
2280 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2281 return createCXString(B->getType().getAsString());
2282 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002283 case CXCursor_TypeRef: {
2284 TypeDecl *Type = getCursorTypeRef(C).first;
2285 assert(Type && "Missing type decl");
2286
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002287 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2288 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002289 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002290 case CXCursor_TemplateRef: {
2291 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002292 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002293
2294 return createCXString(Template->getNameAsString());
2295 }
Douglas Gregor69319002010-08-31 23:48:11 +00002296
2297 case CXCursor_NamespaceRef: {
2298 NamedDecl *NS = getCursorNamespaceRef(C).first;
2299 assert(NS && "Missing namespace decl");
2300
2301 return createCXString(NS->getNameAsString());
2302 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002303
Daniel Dunbaracca7252009-11-30 20:42:49 +00002304 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002305 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002306 }
2307 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002308
2309 if (clang_isExpression(C.kind)) {
2310 Decl *D = getDeclFromExpr(getCursorExpr(C));
2311 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002312 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002313 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002314 }
2315
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002316 if (C.kind == CXCursor_MacroInstantiation)
2317 return createCXString(getCursorMacroInstantiation(C)->getName()
2318 ->getNameStart());
2319
Douglas Gregor572feb22010-03-18 18:04:21 +00002320 if (C.kind == CXCursor_MacroDefinition)
2321 return createCXString(getCursorMacroDefinition(C)->getName()
2322 ->getNameStart());
2323
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002324 if (clang_isDeclaration(C.kind))
2325 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002326
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002327 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002328}
2329
Ted Kremeneke68fff62010-02-17 00:41:32 +00002330CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002331 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002332 case CXCursor_FunctionDecl:
2333 return createCXString("FunctionDecl");
2334 case CXCursor_TypedefDecl:
2335 return createCXString("TypedefDecl");
2336 case CXCursor_EnumDecl:
2337 return createCXString("EnumDecl");
2338 case CXCursor_EnumConstantDecl:
2339 return createCXString("EnumConstantDecl");
2340 case CXCursor_StructDecl:
2341 return createCXString("StructDecl");
2342 case CXCursor_UnionDecl:
2343 return createCXString("UnionDecl");
2344 case CXCursor_ClassDecl:
2345 return createCXString("ClassDecl");
2346 case CXCursor_FieldDecl:
2347 return createCXString("FieldDecl");
2348 case CXCursor_VarDecl:
2349 return createCXString("VarDecl");
2350 case CXCursor_ParmDecl:
2351 return createCXString("ParmDecl");
2352 case CXCursor_ObjCInterfaceDecl:
2353 return createCXString("ObjCInterfaceDecl");
2354 case CXCursor_ObjCCategoryDecl:
2355 return createCXString("ObjCCategoryDecl");
2356 case CXCursor_ObjCProtocolDecl:
2357 return createCXString("ObjCProtocolDecl");
2358 case CXCursor_ObjCPropertyDecl:
2359 return createCXString("ObjCPropertyDecl");
2360 case CXCursor_ObjCIvarDecl:
2361 return createCXString("ObjCIvarDecl");
2362 case CXCursor_ObjCInstanceMethodDecl:
2363 return createCXString("ObjCInstanceMethodDecl");
2364 case CXCursor_ObjCClassMethodDecl:
2365 return createCXString("ObjCClassMethodDecl");
2366 case CXCursor_ObjCImplementationDecl:
2367 return createCXString("ObjCImplementationDecl");
2368 case CXCursor_ObjCCategoryImplDecl:
2369 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002370 case CXCursor_CXXMethod:
2371 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002372 case CXCursor_UnexposedDecl:
2373 return createCXString("UnexposedDecl");
2374 case CXCursor_ObjCSuperClassRef:
2375 return createCXString("ObjCSuperClassRef");
2376 case CXCursor_ObjCProtocolRef:
2377 return createCXString("ObjCProtocolRef");
2378 case CXCursor_ObjCClassRef:
2379 return createCXString("ObjCClassRef");
2380 case CXCursor_TypeRef:
2381 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002382 case CXCursor_TemplateRef:
2383 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002384 case CXCursor_NamespaceRef:
2385 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002386 case CXCursor_UnexposedExpr:
2387 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002388 case CXCursor_BlockExpr:
2389 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002390 case CXCursor_DeclRefExpr:
2391 return createCXString("DeclRefExpr");
2392 case CXCursor_MemberRefExpr:
2393 return createCXString("MemberRefExpr");
2394 case CXCursor_CallExpr:
2395 return createCXString("CallExpr");
2396 case CXCursor_ObjCMessageExpr:
2397 return createCXString("ObjCMessageExpr");
2398 case CXCursor_UnexposedStmt:
2399 return createCXString("UnexposedStmt");
2400 case CXCursor_InvalidFile:
2401 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002402 case CXCursor_InvalidCode:
2403 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002404 case CXCursor_NoDeclFound:
2405 return createCXString("NoDeclFound");
2406 case CXCursor_NotImplemented:
2407 return createCXString("NotImplemented");
2408 case CXCursor_TranslationUnit:
2409 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002410 case CXCursor_UnexposedAttr:
2411 return createCXString("UnexposedAttr");
2412 case CXCursor_IBActionAttr:
2413 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002414 case CXCursor_IBOutletAttr:
2415 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002416 case CXCursor_IBOutletCollectionAttr:
2417 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002418 case CXCursor_PreprocessingDirective:
2419 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002420 case CXCursor_MacroDefinition:
2421 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002422 case CXCursor_MacroInstantiation:
2423 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002424 case CXCursor_Namespace:
2425 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002426 case CXCursor_LinkageSpec:
2427 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002428 case CXCursor_CXXBaseSpecifier:
2429 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002430 case CXCursor_Constructor:
2431 return createCXString("CXXConstructor");
2432 case CXCursor_Destructor:
2433 return createCXString("CXXDestructor");
2434 case CXCursor_ConversionFunction:
2435 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002436 case CXCursor_TemplateTypeParameter:
2437 return createCXString("TemplateTypeParameter");
2438 case CXCursor_NonTypeTemplateParameter:
2439 return createCXString("NonTypeTemplateParameter");
2440 case CXCursor_TemplateTemplateParameter:
2441 return createCXString("TemplateTemplateParameter");
2442 case CXCursor_FunctionTemplate:
2443 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002444 case CXCursor_ClassTemplate:
2445 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002446 case CXCursor_ClassTemplatePartialSpecialization:
2447 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002448 case CXCursor_NamespaceAlias:
2449 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002450 case CXCursor_UsingDirective:
2451 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002452 case CXCursor_UsingDeclaration:
2453 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002454 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002455
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002456 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002457 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002458}
Steve Naroff89922f82009-08-31 00:59:03 +00002459
Ted Kremeneke68fff62010-02-17 00:41:32 +00002460enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2461 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002462 CXClientData client_data) {
2463 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2464 *BestCursor = cursor;
2465 return CXChildVisit_Recurse;
2466}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002467
Douglas Gregorb9790342010-01-22 21:44:22 +00002468CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2469 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002470 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002471
Douglas Gregorb9790342010-01-22 21:44:22 +00002472 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002473 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2474
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002475 // Translate the given source location to make it point at the beginning of
2476 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002477 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002478
2479 // Guard against an invalid SourceLocation, or we may assert in one
2480 // of the following calls.
2481 if (SLoc.isInvalid())
2482 return clang_getNullCursor();
2483
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002484 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2485 CXXUnit->getASTContext().getLangOptions());
2486
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002487 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2488 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002489 // FIXME: Would be great to have a "hint" cursor, then walk from that
2490 // hint cursor upward until we find a cursor whose source range encloses
2491 // the region of interest, rather than starting from the translation unit.
2492 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002493 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002494 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002495 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002496 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002497 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002498}
2499
Ted Kremenek73885552009-11-17 19:28:59 +00002500CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002501 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002502}
2503
2504unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002505 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002506}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002507
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002508unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002509 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2510}
2511
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002512unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002513 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2514}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002515
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002516unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002517 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2518}
2519
Douglas Gregor97b98722010-01-19 23:20:36 +00002520unsigned clang_isExpression(enum CXCursorKind K) {
2521 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2522}
2523
2524unsigned clang_isStatement(enum CXCursorKind K) {
2525 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2526}
2527
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002528unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2529 return K == CXCursor_TranslationUnit;
2530}
2531
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002532unsigned clang_isPreprocessing(enum CXCursorKind K) {
2533 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2534}
2535
Ted Kremenekad6eff62010-03-08 21:17:29 +00002536unsigned clang_isUnexposed(enum CXCursorKind K) {
2537 switch (K) {
2538 case CXCursor_UnexposedDecl:
2539 case CXCursor_UnexposedExpr:
2540 case CXCursor_UnexposedStmt:
2541 case CXCursor_UnexposedAttr:
2542 return true;
2543 default:
2544 return false;
2545 }
2546}
2547
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002548CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002549 return C.kind;
2550}
2551
Douglas Gregor98258af2010-01-18 22:46:11 +00002552CXSourceLocation clang_getCursorLocation(CXCursor C) {
2553 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002554 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002555 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002556 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2557 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002558 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002559 }
2560
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002561 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002562 std::pair<ObjCProtocolDecl *, SourceLocation> P
2563 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002564 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002565 }
2566
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002567 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002568 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2569 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002570 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002571 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002572
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002573 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002574 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002575 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002576 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002577
2578 case CXCursor_TemplateRef: {
2579 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2580 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2581 }
2582
Douglas Gregor69319002010-08-31 23:48:11 +00002583 case CXCursor_NamespaceRef: {
2584 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2585 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2586 }
2587
Ted Kremenek3064ef92010-08-27 21:34:58 +00002588 case CXCursor_CXXBaseSpecifier: {
2589 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2590 return clang_getNullLocation();
2591 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002592
Douglas Gregorf46034a2010-01-18 23:41:10 +00002593 default:
2594 // FIXME: Need a way to enumerate all non-reference cases.
2595 llvm_unreachable("Missed a reference kind");
2596 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002597 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002598
2599 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002600 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002601 getLocationFromExpr(getCursorExpr(C)));
2602
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002603 if (C.kind == CXCursor_PreprocessingDirective) {
2604 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2605 return cxloc::translateSourceLocation(getCursorContext(C), L);
2606 }
Douglas Gregor48072312010-03-18 15:23:44 +00002607
2608 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002609 SourceLocation L
2610 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002611 return cxloc::translateSourceLocation(getCursorContext(C), L);
2612 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002613
2614 if (C.kind == CXCursor_MacroDefinition) {
2615 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2616 return cxloc::translateSourceLocation(getCursorContext(C), L);
2617 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002618
Ted Kremenek9a700d22010-05-12 06:16:13 +00002619 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002620 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002621
Douglas Gregorf46034a2010-01-18 23:41:10 +00002622 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002623 SourceLocation Loc = D->getLocation();
2624 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2625 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002626 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002627}
Douglas Gregora7bde202010-01-19 00:34:46 +00002628
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002629} // end extern "C"
2630
2631static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002632 if (clang_isReference(C.kind)) {
2633 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002634 case CXCursor_ObjCSuperClassRef:
2635 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002636
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002637 case CXCursor_ObjCProtocolRef:
2638 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002639
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002640 case CXCursor_ObjCClassRef:
2641 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002642
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002643 case CXCursor_TypeRef:
2644 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002645
2646 case CXCursor_TemplateRef:
2647 return getCursorTemplateRef(C).second;
2648
Douglas Gregor69319002010-08-31 23:48:11 +00002649 case CXCursor_NamespaceRef:
2650 return getCursorNamespaceRef(C).second;
2651
Ted Kremenek3064ef92010-08-27 21:34:58 +00002652 case CXCursor_CXXBaseSpecifier:
2653 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2654 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002655
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002656 default:
2657 // FIXME: Need a way to enumerate all non-reference cases.
2658 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002659 }
2660 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002661
2662 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002663 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002664
2665 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002666 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002667
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002668 if (C.kind == CXCursor_PreprocessingDirective)
2669 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002670
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002671 if (C.kind == CXCursor_MacroInstantiation)
2672 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002673
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002674 if (C.kind == CXCursor_MacroDefinition)
2675 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002676
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002677 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2678 return getCursorDecl(C)->getSourceRange();
2679
2680 return SourceRange();
2681}
2682
2683extern "C" {
2684
2685CXSourceRange clang_getCursorExtent(CXCursor C) {
2686 SourceRange R = getRawCursorExtent(C);
2687 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002688 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002689
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002690 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002691}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002692
2693CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002694 if (clang_isInvalid(C.kind))
2695 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002696
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002697 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002698 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002699 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002700
Douglas Gregor97b98722010-01-19 23:20:36 +00002701 if (clang_isExpression(C.kind)) {
2702 Decl *D = getDeclFromExpr(getCursorExpr(C));
2703 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002704 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002705 return clang_getNullCursor();
2706 }
2707
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002708 if (C.kind == CXCursor_MacroInstantiation) {
2709 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2710 return MakeMacroDefinitionCursor(Def, CXXUnit);
2711 }
2712
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002713 if (!clang_isReference(C.kind))
2714 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002715
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002716 switch (C.kind) {
2717 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002718 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002719
2720 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002721 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002722
2723 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002724 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002725
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002726 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002727 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002728
2729 case CXCursor_TemplateRef:
2730 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2731
Douglas Gregor69319002010-08-31 23:48:11 +00002732 case CXCursor_NamespaceRef:
2733 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2734
Ted Kremenek3064ef92010-08-27 21:34:58 +00002735 case CXCursor_CXXBaseSpecifier: {
2736 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2737 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2738 CXXUnit));
2739 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002740
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002741 default:
2742 // We would prefer to enumerate all non-reference cursor kinds here.
2743 llvm_unreachable("Unhandled reference cursor kind");
2744 break;
2745 }
2746 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002747
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002748 return clang_getNullCursor();
2749}
2750
Douglas Gregorb6998662010-01-19 19:34:47 +00002751CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002752 if (clang_isInvalid(C.kind))
2753 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002754
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002755 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002756
Douglas Gregorb6998662010-01-19 19:34:47 +00002757 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002758 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002759 C = clang_getCursorReferenced(C);
2760 WasReference = true;
2761 }
2762
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002763 if (C.kind == CXCursor_MacroInstantiation)
2764 return clang_getCursorReferenced(C);
2765
Douglas Gregorb6998662010-01-19 19:34:47 +00002766 if (!clang_isDeclaration(C.kind))
2767 return clang_getNullCursor();
2768
2769 Decl *D = getCursorDecl(C);
2770 if (!D)
2771 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002772
Douglas Gregorb6998662010-01-19 19:34:47 +00002773 switch (D->getKind()) {
2774 // Declaration kinds that don't really separate the notions of
2775 // declaration and definition.
2776 case Decl::Namespace:
2777 case Decl::Typedef:
2778 case Decl::TemplateTypeParm:
2779 case Decl::EnumConstant:
2780 case Decl::Field:
2781 case Decl::ObjCIvar:
2782 case Decl::ObjCAtDefsField:
2783 case Decl::ImplicitParam:
2784 case Decl::ParmVar:
2785 case Decl::NonTypeTemplateParm:
2786 case Decl::TemplateTemplateParm:
2787 case Decl::ObjCCategoryImpl:
2788 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002789 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002790 case Decl::LinkageSpec:
2791 case Decl::ObjCPropertyImpl:
2792 case Decl::FileScopeAsm:
2793 case Decl::StaticAssert:
2794 case Decl::Block:
2795 return C;
2796
2797 // Declaration kinds that don't make any sense here, but are
2798 // nonetheless harmless.
2799 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002800 break;
2801
2802 // Declaration kinds for which the definition is not resolvable.
2803 case Decl::UnresolvedUsingTypename:
2804 case Decl::UnresolvedUsingValue:
2805 break;
2806
2807 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002808 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2809 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002810
2811 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002812 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002813
2814 case Decl::Enum:
2815 case Decl::Record:
2816 case Decl::CXXRecord:
2817 case Decl::ClassTemplateSpecialization:
2818 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002819 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002820 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002821 return clang_getNullCursor();
2822
2823 case Decl::Function:
2824 case Decl::CXXMethod:
2825 case Decl::CXXConstructor:
2826 case Decl::CXXDestructor:
2827 case Decl::CXXConversion: {
2828 const FunctionDecl *Def = 0;
2829 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002830 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002831 return clang_getNullCursor();
2832 }
2833
2834 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002835 // Ask the variable if it has a definition.
2836 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2837 return MakeCXCursor(Def, CXXUnit);
2838 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002839 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002840
Douglas Gregorb6998662010-01-19 19:34:47 +00002841 case Decl::FunctionTemplate: {
2842 const FunctionDecl *Def = 0;
2843 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002844 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002845 return clang_getNullCursor();
2846 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002847
Douglas Gregorb6998662010-01-19 19:34:47 +00002848 case Decl::ClassTemplate: {
2849 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002850 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002851 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002852 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002853 return clang_getNullCursor();
2854 }
2855
2856 case Decl::Using: {
2857 UsingDecl *Using = cast<UsingDecl>(D);
2858 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002859 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2860 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002861 S != SEnd; ++S) {
2862 if (Def != clang_getNullCursor()) {
2863 // FIXME: We have no way to return multiple results.
2864 return clang_getNullCursor();
2865 }
2866
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002867 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002868 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002869 }
2870
2871 return Def;
2872 }
2873
2874 case Decl::UsingShadow:
2875 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002876 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002877 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002878
2879 case Decl::ObjCMethod: {
2880 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2881 if (Method->isThisDeclarationADefinition())
2882 return C;
2883
2884 // Dig out the method definition in the associated
2885 // @implementation, if we have it.
2886 // FIXME: The ASTs should make finding the definition easier.
2887 if (ObjCInterfaceDecl *Class
2888 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2889 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2890 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2891 Method->isInstanceMethod()))
2892 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002893 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002894
2895 return clang_getNullCursor();
2896 }
2897
2898 case Decl::ObjCCategory:
2899 if (ObjCCategoryImplDecl *Impl
2900 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002901 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002902 return clang_getNullCursor();
2903
2904 case Decl::ObjCProtocol:
2905 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2906 return C;
2907 return clang_getNullCursor();
2908
2909 case Decl::ObjCInterface:
2910 // There are two notions of a "definition" for an Objective-C
2911 // class: the interface and its implementation. When we resolved a
2912 // reference to an Objective-C class, produce the @interface as
2913 // the definition; when we were provided with the interface,
2914 // produce the @implementation as the definition.
2915 if (WasReference) {
2916 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2917 return C;
2918 } else if (ObjCImplementationDecl *Impl
2919 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002920 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002921 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002922
Douglas Gregorb6998662010-01-19 19:34:47 +00002923 case Decl::ObjCProperty:
2924 // FIXME: We don't really know where to find the
2925 // ObjCPropertyImplDecls that implement this property.
2926 return clang_getNullCursor();
2927
2928 case Decl::ObjCCompatibleAlias:
2929 if (ObjCInterfaceDecl *Class
2930 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2931 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002932 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002933
Douglas Gregorb6998662010-01-19 19:34:47 +00002934 return clang_getNullCursor();
2935
2936 case Decl::ObjCForwardProtocol: {
2937 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2938 if (Forward->protocol_size() == 1)
2939 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002940 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002941 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002942
2943 // FIXME: Cannot return multiple definitions.
2944 return clang_getNullCursor();
2945 }
2946
2947 case Decl::ObjCClass: {
2948 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2949 if (Class->size() == 1) {
2950 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2951 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002952 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002953 return clang_getNullCursor();
2954 }
2955
2956 // FIXME: Cannot return multiple definitions.
2957 return clang_getNullCursor();
2958 }
2959
2960 case Decl::Friend:
2961 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002962 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002963 return clang_getNullCursor();
2964
2965 case Decl::FriendTemplate:
2966 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002967 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002968 return clang_getNullCursor();
2969 }
2970
2971 return clang_getNullCursor();
2972}
2973
2974unsigned clang_isCursorDefinition(CXCursor C) {
2975 if (!clang_isDeclaration(C.kind))
2976 return 0;
2977
2978 return clang_getCursorDefinition(C) == C;
2979}
2980
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002981void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002982 const char **startBuf,
2983 const char **endBuf,
2984 unsigned *startLine,
2985 unsigned *startColumn,
2986 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002987 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002988 assert(getCursorDecl(C) && "CXCursor has null decl");
2989 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002990 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2991 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002992
Steve Naroff4ade6d62009-09-23 17:52:52 +00002993 SourceManager &SM = FD->getASTContext().getSourceManager();
2994 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2995 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2996 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2997 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2998 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2999 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3000}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003001
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003002void clang_enableStackTraces(void) {
3003 llvm::sys::PrintStackTraceOnErrorSignal();
3004}
3005
Ted Kremenekfb480492010-01-13 21:46:36 +00003006} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003007
Ted Kremenekfb480492010-01-13 21:46:36 +00003008//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003009// Token-based Operations.
3010//===----------------------------------------------------------------------===//
3011
3012/* CXToken layout:
3013 * int_data[0]: a CXTokenKind
3014 * int_data[1]: starting token location
3015 * int_data[2]: token length
3016 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003017 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003018 * otherwise unused.
3019 */
3020extern "C" {
3021
3022CXTokenKind clang_getTokenKind(CXToken CXTok) {
3023 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3024}
3025
3026CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3027 switch (clang_getTokenKind(CXTok)) {
3028 case CXToken_Identifier:
3029 case CXToken_Keyword:
3030 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003031 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3032 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003033
3034 case CXToken_Literal: {
3035 // We have stashed the starting pointer in the ptr_data field. Use it.
3036 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003037 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003038 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003039
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003040 case CXToken_Punctuation:
3041 case CXToken_Comment:
3042 break;
3043 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003044
3045 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003046 // deconstructing the source location.
3047 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3048 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003049 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003050
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003051 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3052 std::pair<FileID, unsigned> LocInfo
3053 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003054 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003055 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003056 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3057 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003058 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003059
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003060 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003061}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003062
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003063CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3064 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3065 if (!CXXUnit)
3066 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003067
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003068 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3069 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3070}
3071
3072CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3073 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003074 if (!CXXUnit)
3075 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003076
3077 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003078 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3079}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003080
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003081void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3082 CXToken **Tokens, unsigned *NumTokens) {
3083 if (Tokens)
3084 *Tokens = 0;
3085 if (NumTokens)
3086 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003087
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003088 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3089 if (!CXXUnit || !Tokens || !NumTokens)
3090 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003091
Douglas Gregorbdf60622010-03-05 21:16:25 +00003092 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3093
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003094 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003095 if (R.isInvalid())
3096 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003097
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003098 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3099 std::pair<FileID, unsigned> BeginLocInfo
3100 = SourceMgr.getDecomposedLoc(R.getBegin());
3101 std::pair<FileID, unsigned> EndLocInfo
3102 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003103
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003104 // Cannot tokenize across files.
3105 if (BeginLocInfo.first != EndLocInfo.first)
3106 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003107
3108 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003109 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003110 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003111 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003112 if (Invalid)
3113 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003114
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003115 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3116 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003117 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003118 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003119
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003120 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003121 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003122 llvm::SmallVector<CXToken, 32> CXTokens;
3123 Token Tok;
3124 do {
3125 // Lex the next token
3126 Lex.LexFromRawLexer(Tok);
3127 if (Tok.is(tok::eof))
3128 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003129
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003130 // Initialize the CXToken.
3131 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003132
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003133 // - Common fields
3134 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3135 CXTok.int_data[2] = Tok.getLength();
3136 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003137
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003138 // - Kind-specific fields
3139 if (Tok.isLiteral()) {
3140 CXTok.int_data[0] = CXToken_Literal;
3141 CXTok.ptr_data = (void *)Tok.getLiteralData();
3142 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003143 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003144 std::pair<FileID, unsigned> LocInfo
3145 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003146 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003147 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003148 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3149 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003150 return;
3151
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003152 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003153 IdentifierInfo *II
3154 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003155
3156 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3157 CXTok.int_data[0] = CXToken_Keyword;
3158 }
3159 else {
3160 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3161 CXToken_Identifier
3162 : CXToken_Keyword;
3163 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003164 CXTok.ptr_data = II;
3165 } else if (Tok.is(tok::comment)) {
3166 CXTok.int_data[0] = CXToken_Comment;
3167 CXTok.ptr_data = 0;
3168 } else {
3169 CXTok.int_data[0] = CXToken_Punctuation;
3170 CXTok.ptr_data = 0;
3171 }
3172 CXTokens.push_back(CXTok);
3173 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003174
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003175 if (CXTokens.empty())
3176 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003177
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003178 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3179 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3180 *NumTokens = CXTokens.size();
3181}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003182
Ted Kremenek6db61092010-05-05 00:55:15 +00003183void clang_disposeTokens(CXTranslationUnit TU,
3184 CXToken *Tokens, unsigned NumTokens) {
3185 free(Tokens);
3186}
3187
3188} // end: extern "C"
3189
3190//===----------------------------------------------------------------------===//
3191// Token annotation APIs.
3192//===----------------------------------------------------------------------===//
3193
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003194typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003195static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3196 CXCursor parent,
3197 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003198namespace {
3199class AnnotateTokensWorker {
3200 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003201 CXToken *Tokens;
3202 CXCursor *Cursors;
3203 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003204 unsigned TokIdx;
3205 CursorVisitor AnnotateVis;
3206 SourceManager &SrcMgr;
3207
3208 bool MoreTokens() const { return TokIdx < NumTokens; }
3209 unsigned NextToken() const { return TokIdx; }
3210 void AdvanceToken() { ++TokIdx; }
3211 SourceLocation GetTokenLoc(unsigned tokI) {
3212 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3213 }
3214
Ted Kremenek6db61092010-05-05 00:55:15 +00003215public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003216 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003217 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3218 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003219 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003220 NumTokens(numTokens), TokIdx(0),
3221 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3222 Decl::MaxPCHLevel, RegionOfInterest),
3223 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003224
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003225 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003226 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003227 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003228};
3229}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003230
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003231void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3232 // Walk the AST within the region of interest, annotating tokens
3233 // along the way.
3234 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003235
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003236 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3237 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3238 if (Pos != Annotated.end())
3239 Cursors[I] = Pos->second;
3240 }
3241
3242 // Finish up annotating any tokens left.
3243 if (!MoreTokens())
3244 return;
3245
3246 const CXCursor &C = clang_getNullCursor();
3247 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3248 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3249 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003250 }
3251}
3252
Ted Kremenek6db61092010-05-05 00:55:15 +00003253enum CXChildVisitResult
3254AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003255 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3256 // We can always annotate a preprocessing directive/macro instantiation.
3257 if (clang_isPreprocessing(cursor.kind)) {
3258 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003259 return CXChildVisit_Recurse;
3260 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003261
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003262 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003263
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003264 if (cursorRange.isInvalid())
3265 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003266
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003267 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3268
Ted Kremeneka333c662010-05-12 05:29:33 +00003269 // Adjust the annotated range based specific declarations.
3270 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3271 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003272 Decl *D = cxcursor::getCursorDecl(cursor);
3273 // Don't visit synthesized ObjC methods, since they have no syntatic
3274 // representation in the source.
3275 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3276 if (MD->isSynthesized())
3277 return CXChildVisit_Continue;
3278 }
3279 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003280 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3281 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003282 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003283 if (TLoc.isValid() &&
3284 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003285 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003286 }
3287 }
3288 }
3289
Ted Kremenek3f404602010-08-14 01:14:06 +00003290 // If the location of the cursor occurs within a macro instantiation, record
3291 // the spelling location of the cursor in our annotation map. We can then
3292 // paper over the token labelings during a post-processing step to try and
3293 // get cursor mappings for tokens that are the *arguments* of a macro
3294 // instantiation.
3295 if (L.isMacroID()) {
3296 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3297 // Only invalidate the old annotation if it isn't part of a preprocessing
3298 // directive. Here we assume that the default construction of CXCursor
3299 // results in CXCursor.kind being an initialized value (i.e., 0). If
3300 // this isn't the case, we can fix by doing lookup + insertion.
3301
3302 CXCursor &oldC = Annotated[rawEncoding];
3303 if (!clang_isPreprocessing(oldC.kind))
3304 oldC = cursor;
3305 }
3306
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003307 const enum CXCursorKind K = clang_getCursorKind(parent);
3308 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003309 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3310 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003311
3312 while (MoreTokens()) {
3313 const unsigned I = NextToken();
3314 SourceLocation TokLoc = GetTokenLoc(I);
3315 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3316 case RangeBefore:
3317 Cursors[I] = updateC;
3318 AdvanceToken();
3319 continue;
3320 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003321 case RangeOverlap:
3322 break;
3323 }
3324 break;
3325 }
3326
3327 // Visit children to get their cursor information.
3328 const unsigned BeforeChildren = NextToken();
3329 VisitChildren(cursor);
3330 const unsigned AfterChildren = NextToken();
3331
3332 // Adjust 'Last' to the last token within the extent of the cursor.
3333 while (MoreTokens()) {
3334 const unsigned I = NextToken();
3335 SourceLocation TokLoc = GetTokenLoc(I);
3336 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3337 case RangeBefore:
3338 assert(0 && "Infeasible");
3339 case RangeAfter:
3340 break;
3341 case RangeOverlap:
3342 Cursors[I] = updateC;
3343 AdvanceToken();
3344 continue;
3345 }
3346 break;
3347 }
3348 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003349
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003350 // Scan the tokens that are at the beginning of the cursor, but are not
3351 // capture by the child cursors.
3352
3353 // For AST elements within macros, rely on a post-annotate pass to
3354 // to correctly annotate the tokens with cursors. Otherwise we can
3355 // get confusing results of having tokens that map to cursors that really
3356 // are expanded by an instantiation.
3357 if (L.isMacroID())
3358 cursor = clang_getNullCursor();
3359
3360 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3361 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3362 break;
3363 Cursors[I] = cursor;
3364 }
3365 // Scan the tokens that are at the end of the cursor, but are not captured
3366 // but the child cursors.
3367 for (unsigned I = AfterChildren; I != Last; ++I)
3368 Cursors[I] = cursor;
3369
3370 TokIdx = Last;
3371 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003372}
3373
Ted Kremenek6db61092010-05-05 00:55:15 +00003374static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3375 CXCursor parent,
3376 CXClientData client_data) {
3377 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3378}
3379
3380extern "C" {
3381
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003382void clang_annotateTokens(CXTranslationUnit TU,
3383 CXToken *Tokens, unsigned NumTokens,
3384 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003385
3386 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003387 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003388
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003389 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003390 if (!CXXUnit) {
3391 // Any token we don't specifically annotate will have a NULL cursor.
3392 const CXCursor &C = clang_getNullCursor();
3393 for (unsigned I = 0; I != NumTokens; ++I)
3394 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003395 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003396 }
3397
Douglas Gregorbdf60622010-03-05 21:16:25 +00003398 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003399
Douglas Gregor0396f462010-03-19 05:22:59 +00003400 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003401 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003402 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3403 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003404 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3405 clang_getTokenLocation(TU,
3406 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003407
Douglas Gregor0396f462010-03-19 05:22:59 +00003408 // A mapping from the source locations found when re-lexing or traversing the
3409 // region of interest to the corresponding cursors.
3410 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003411
3412 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003413 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003414 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3415 std::pair<FileID, unsigned> BeginLocInfo
3416 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3417 std::pair<FileID, unsigned> EndLocInfo
3418 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003419
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003420 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003421 bool Invalid = false;
3422 if (BeginLocInfo.first == EndLocInfo.first &&
3423 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3424 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003425 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3426 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003427 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003428 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003429 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003430
3431 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003432 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003433 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003434 Token Tok;
3435 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003436
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003437 reprocess:
3438 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3439 // We have found a preprocessing directive. Gobble it up so that we
3440 // don't see it while preprocessing these tokens later, but keep track of
3441 // all of the token locations inside this preprocessing directive so that
3442 // we can annotate them appropriately.
3443 //
3444 // FIXME: Some simple tests here could identify macro definitions and
3445 // #undefs, to provide specific cursor kinds for those.
3446 std::vector<SourceLocation> Locations;
3447 do {
3448 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003449 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003450 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003451
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003452 using namespace cxcursor;
3453 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003454 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3455 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003456 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003457 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3458 Annotated[Locations[I].getRawEncoding()] = Cursor;
3459 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003460
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003461 if (Tok.isAtStartOfLine())
3462 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003463
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003464 continue;
3465 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003466
Douglas Gregor48072312010-03-18 15:23:44 +00003467 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003468 break;
3469 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003470 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003471
Douglas Gregor0396f462010-03-19 05:22:59 +00003472 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003473 // a specific cursor.
3474 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3475 CXXUnit, RegionOfInterest);
3476 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003477}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003478} // end: extern "C"
3479
3480//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003481// Operations for querying linkage of a cursor.
3482//===----------------------------------------------------------------------===//
3483
3484extern "C" {
3485CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003486 if (!clang_isDeclaration(cursor.kind))
3487 return CXLinkage_Invalid;
3488
Ted Kremenek16b42592010-03-03 06:36:57 +00003489 Decl *D = cxcursor::getCursorDecl(cursor);
3490 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3491 switch (ND->getLinkage()) {
3492 case NoLinkage: return CXLinkage_NoLinkage;
3493 case InternalLinkage: return CXLinkage_Internal;
3494 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3495 case ExternalLinkage: return CXLinkage_External;
3496 };
3497
3498 return CXLinkage_Invalid;
3499}
3500} // end: extern "C"
3501
3502//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003503// Operations for querying language of a cursor.
3504//===----------------------------------------------------------------------===//
3505
3506static CXLanguageKind getDeclLanguage(const Decl *D) {
3507 switch (D->getKind()) {
3508 default:
3509 break;
3510 case Decl::ImplicitParam:
3511 case Decl::ObjCAtDefsField:
3512 case Decl::ObjCCategory:
3513 case Decl::ObjCCategoryImpl:
3514 case Decl::ObjCClass:
3515 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003516 case Decl::ObjCForwardProtocol:
3517 case Decl::ObjCImplementation:
3518 case Decl::ObjCInterface:
3519 case Decl::ObjCIvar:
3520 case Decl::ObjCMethod:
3521 case Decl::ObjCProperty:
3522 case Decl::ObjCPropertyImpl:
3523 case Decl::ObjCProtocol:
3524 return CXLanguage_ObjC;
3525 case Decl::CXXConstructor:
3526 case Decl::CXXConversion:
3527 case Decl::CXXDestructor:
3528 case Decl::CXXMethod:
3529 case Decl::CXXRecord:
3530 case Decl::ClassTemplate:
3531 case Decl::ClassTemplatePartialSpecialization:
3532 case Decl::ClassTemplateSpecialization:
3533 case Decl::Friend:
3534 case Decl::FriendTemplate:
3535 case Decl::FunctionTemplate:
3536 case Decl::LinkageSpec:
3537 case Decl::Namespace:
3538 case Decl::NamespaceAlias:
3539 case Decl::NonTypeTemplateParm:
3540 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003541 case Decl::TemplateTemplateParm:
3542 case Decl::TemplateTypeParm:
3543 case Decl::UnresolvedUsingTypename:
3544 case Decl::UnresolvedUsingValue:
3545 case Decl::Using:
3546 case Decl::UsingDirective:
3547 case Decl::UsingShadow:
3548 return CXLanguage_CPlusPlus;
3549 }
3550
3551 return CXLanguage_C;
3552}
3553
3554extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003555
3556enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3557 if (clang_isDeclaration(cursor.kind))
3558 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3559 if (D->hasAttr<UnavailableAttr>() ||
3560 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3561 return CXAvailability_Available;
3562
3563 if (D->hasAttr<DeprecatedAttr>())
3564 return CXAvailability_Deprecated;
3565 }
3566
3567 return CXAvailability_Available;
3568}
3569
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003570CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3571 if (clang_isDeclaration(cursor.kind))
3572 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3573
3574 return CXLanguage_Invalid;
3575}
3576} // end: extern "C"
3577
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003578
3579//===----------------------------------------------------------------------===//
3580// C++ AST instrospection.
3581//===----------------------------------------------------------------------===//
3582
3583extern "C" {
3584unsigned clang_CXXMethod_isStatic(CXCursor C) {
3585 if (!clang_isDeclaration(C.kind))
3586 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003587
3588 CXXMethodDecl *Method = 0;
3589 Decl *D = cxcursor::getCursorDecl(C);
3590 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3591 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3592 else
3593 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3594 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003595}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003596
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003597} // end: extern "C"
3598
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003599//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003600// Attribute introspection.
3601//===----------------------------------------------------------------------===//
3602
3603extern "C" {
3604CXType clang_getIBOutletCollectionType(CXCursor C) {
3605 if (C.kind != CXCursor_IBOutletCollectionAttr)
3606 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3607
3608 IBOutletCollectionAttr *A =
3609 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3610
3611 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3612}
3613} // end: extern "C"
3614
3615//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003616// CXString Operations.
3617//===----------------------------------------------------------------------===//
3618
3619extern "C" {
3620const char *clang_getCString(CXString string) {
3621 return string.Spelling;
3622}
3623
3624void clang_disposeString(CXString string) {
3625 if (string.MustFreeString && string.Spelling)
3626 free((void*)string.Spelling);
3627}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003628
Ted Kremenekfb480492010-01-13 21:46:36 +00003629} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003630
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003631namespace clang { namespace cxstring {
3632CXString createCXString(const char *String, bool DupString){
3633 CXString Str;
3634 if (DupString) {
3635 Str.Spelling = strdup(String);
3636 Str.MustFreeString = 1;
3637 } else {
3638 Str.Spelling = String;
3639 Str.MustFreeString = 0;
3640 }
3641 return Str;
3642}
3643
3644CXString createCXString(llvm::StringRef String, bool DupString) {
3645 CXString Result;
3646 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3647 char *Spelling = (char *)malloc(String.size() + 1);
3648 memmove(Spelling, String.data(), String.size());
3649 Spelling[String.size()] = 0;
3650 Result.Spelling = Spelling;
3651 Result.MustFreeString = 1;
3652 } else {
3653 Result.Spelling = String.data();
3654 Result.MustFreeString = 0;
3655 }
3656 return Result;
3657}
3658}}
3659
Ted Kremenek04bb7162010-01-22 22:44:15 +00003660//===----------------------------------------------------------------------===//
3661// Misc. utility functions.
3662//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003663
Ted Kremenek04bb7162010-01-22 22:44:15 +00003664extern "C" {
3665
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003666CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003667 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003668}
3669
3670} // end: extern "C"