blob: c056e485429dc6ac2e558b19484f0602705e277f [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000033#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor02465752009-10-16 21:24:31 +000034#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000035#include "llvm/Support/Timer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000036#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000037#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000038
Benjamin Kramerc2a98162010-03-13 21:22:49 +000039// Needed to define L_TMPNAM on some systems.
40#include <cstdio>
41
Steve Naroff50398192009-08-28 15:28:48 +000042using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000043using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000044using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000045
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000046//===----------------------------------------------------------------------===//
47// Crash Reporting.
48//===----------------------------------------------------------------------===//
49
Ted Kremenekd7ffd082010-05-22 00:06:46 +000050#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000051#include "clang/Analysis/Support/SaveAndRestore.h"
52// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000053static const char *__crashreporter_info__ = 0;
54asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000055#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000056static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000057static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000058static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
59static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
60
61static unsigned SetCrashTracerInfo(const char *str,
62 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000063
Ted Kremenek254ba7c2010-01-07 23:13:53 +000064 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000065 while (crashtracer_strings[slot]) {
66 if (++slot == NUM_CRASH_STRINGS)
67 slot = 0;
68 }
69 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000070 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000071
72 // We need to create an aggregate string because multiple threads
73 // may be in this method at one time. The crash reporter string
74 // will attempt to overapproximate the set of in-flight invocations
75 // of this function. Race conditions can still cause this goal
76 // to not be achieved.
77 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000078 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000079 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
80 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
81 }
82 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
83 return slot;
84}
85
86static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000087 unsigned max_slot = 0;
88 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000089
Ted Kremenek254ba7c2010-01-07 23:13:53 +000090 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
91
92 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
93 if (agg_crashtracer_strings[i] &&
94 crashtracer_counter_id[i] > max_value) {
95 max_slot = i;
96 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000097 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000098
99 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +0000100}
101
102namespace {
103class ArgsCrashTracerInfo {
104 llvm::SmallString<1024> CrashString;
105 llvm::SmallString<1024> AggregateString;
106 unsigned crashtracerSlot;
107public:
108 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
109 : crashtracerSlot(0)
110 {
111 {
112 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000113 Out << "ClangCIndex [" << getClangFullVersion() << "]"
114 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000115 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
116 E=Args.end(); I!=E; ++I)
117 Out << ' ' << *I;
118 }
119 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
120 AggregateString);
121 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000122
Ted Kremenek29b72842010-01-07 22:49:05 +0000123 ~ArgsCrashTracerInfo() {
124 ResetCrashTracerInfo(crashtracerSlot);
125 }
126};
127}
128#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000129
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000130/// \brief The result of comparing two source ranges.
131enum RangeComparisonResult {
132 /// \brief Either the ranges overlap or one of the ranges is invalid.
133 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135 /// \brief The first range ends before the second range starts.
136 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000137
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000138 /// \brief The first range starts after the second range ends.
139 RangeAfter
140};
141
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000142/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000143/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000144static RangeComparisonResult RangeCompare(SourceManager &SM,
145 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000146 SourceRange R2) {
147 assert(R1.isValid() && "First range is invalid?");
148 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000149 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000150 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000152 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000153 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000154 return RangeAfter;
155 return RangeOverlap;
156}
157
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000158/// \brief Determine if a source location falls within, before, or after a
159/// a given source range.
160static RangeComparisonResult LocationCompare(SourceManager &SM,
161 SourceLocation L, SourceRange R) {
162 assert(R.isValid() && "First range is invalid?");
163 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000164 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000165 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000166 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
167 return RangeBefore;
168 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
169 return RangeAfter;
170 return RangeOverlap;
171}
172
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000173/// \brief Translate a Clang source range into a CIndex source range.
174///
175/// Clang internally represents ranges where the end location points to the
176/// start of the token at the end. However, for external clients it is more
177/// useful to have a CXSourceRange be a proper half-open interval. This routine
178/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000179CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000180 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000181 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000182 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000183 // location accordingly.
184 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000185 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000186 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000187 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000188 EndLoc = EndLoc.getFileLocWithOffset(Length);
189 }
190
191 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
192 R.getBegin().getRawEncoding(),
193 EndLoc.getRawEncoding() };
194 return Result;
195}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000196
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000197//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000198// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000199//===----------------------------------------------------------------------===//
200
Steve Naroff89922f82009-08-31 00:59:03 +0000201namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000202
Douglas Gregorb1373d02010-01-20 20:59:29 +0000203// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000205 public TypeLocVisitor<CursorVisitor, bool>,
206 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000207{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000209 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000211 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000212 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000213
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000214 /// \brief The declaration that serves at the parent of any statement or
215 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000216 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000217
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000219 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000221 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000222 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000223
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000224 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
225 // to the visitor. Declarations with a PCH level greater than this value will
226 // be suppressed.
227 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000228
229 /// \brief When valid, a source range to which the cursor should restrict
230 /// its search.
231 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000232
Douglas Gregorb1373d02010-01-20 20:59:29 +0000233 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000234 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000235 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000236
237 /// \brief Determine whether this particular source range comes before, comes
238 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000239 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000240 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000241 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
242
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000243 class SetParentRAII {
244 CXCursor &Parent;
245 Decl *&StmtParent;
246 CXCursor OldParent;
247
248 public:
249 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
250 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
251 {
252 Parent = NewParent;
253 if (clang_isDeclaration(Parent.kind))
254 StmtParent = getCursorDecl(Parent);
255 }
256
257 ~SetParentRAII() {
258 Parent = OldParent;
259 if (clang_isDeclaration(Parent.kind))
260 StmtParent = getCursorDecl(Parent);
261 }
262 };
263
Steve Naroff89922f82009-08-31 00:59:03 +0000264public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000265 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
266 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000267 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000268 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000269 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000270 {
271 Parent.kind = CXCursor_NoDeclFound;
272 Parent.data[0] = 0;
273 Parent.data[1] = 0;
274 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000275 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000276 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000277
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000278 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000279
280 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
281 getPreprocessedEntities();
282
Douglas Gregorb1373d02010-01-20 20:59:29 +0000283 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000284
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000285 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000286 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000287 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000288 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000289 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000290 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
291 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000292 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000293 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000294 bool VisitClassTemplatePartialSpecializationDecl(
295 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000296 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000297 bool VisitEnumConstantDecl(EnumConstantDecl *D);
298 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
299 bool VisitFunctionDecl(FunctionDecl *ND);
300 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000301 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000302 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000303 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000304 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000305 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000306 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
307 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
308 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
309 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000310 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000311 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
312 bool VisitObjCImplDecl(ObjCImplDecl *D);
313 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
314 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
315 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
316 // etc.
317 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
318 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
319 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000320 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000321 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000322 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000323 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000324 bool VisitUsingDecl(UsingDecl *D);
325 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
326 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000327
Douglas Gregor01829d32010-08-31 14:41:23 +0000328 // Name visitor
329 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000330 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000331
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000332 // Template visitors
333 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000334 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000335 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
336
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000337 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000338 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000339 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000340 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000341 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
342 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000343 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000344 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000345 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000346 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
347 bool VisitPointerTypeLoc(PointerTypeLoc TL);
348 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
349 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
350 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
351 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000352 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000353 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000354 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000355 // FIXME: Implement visitors here when the unimplemented TypeLocs get
356 // implemented
357 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
358 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000359
Douglas Gregora59e3902010-01-21 23:27:09 +0000360 // Statement visitors
361 bool VisitStmt(Stmt *S);
362 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000363 // FIXME: LabelStmt label?
364 bool VisitIfStmt(IfStmt *S);
365 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000366 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000367 bool VisitWhileStmt(WhileStmt *S);
368 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000369// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000370
Douglas Gregor336fd812010-01-23 00:40:08 +0000371 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000372 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000373 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000374 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000375 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000376 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000377 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000378 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000379 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000380 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfbb4c982010-09-02 21:07:44 +0000381 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000382 // FIXME: AddrLabelExpr (once we have cursors for labels)
383 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
384 bool VisitVAArgExpr(VAArgExpr *E);
385 // FIXME: InitListExpr (for the designators)
386 // FIXME: DesignatedInitExpr
Douglas Gregor94802292010-09-02 21:20:16 +0000387 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000388 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregor8ab670e2010-09-02 22:19:24 +0000389 // FIXME: CXXTemporaryObjectExpr has poor source-location information.
390 // FIXME: CXXScalarValueInitExpr has poor source-location information.
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000391 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000392 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor8ab670e2010-09-02 22:19:24 +0000393 // FIXME: UnaryTypeTraitExpr has poor source-location information.
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000394 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000395 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000396 // FIXME: CXXUnresolvedConstructExpr has poor source-location information.
Douglas Gregor25d63622010-09-03 17:35:34 +0000397 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000398 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000399};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000400
Ted Kremenekab188932010-01-05 19:32:54 +0000401} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000402
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000403static SourceRange getRawCursorExtent(CXCursor C);
404
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000405RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000406 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
407}
408
Douglas Gregorb1373d02010-01-20 20:59:29 +0000409/// \brief Visit the given cursor and, if requested by the visitor,
410/// its children.
411///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000412/// \param Cursor the cursor to visit.
413///
414/// \param CheckRegionOfInterest if true, then the caller already checked that
415/// this cursor is within the region of interest.
416///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000417/// \returns true if the visitation should be aborted, false if it
418/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000419bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000420 if (clang_isInvalid(Cursor.kind))
421 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000422
Douglas Gregorb1373d02010-01-20 20:59:29 +0000423 if (clang_isDeclaration(Cursor.kind)) {
424 Decl *D = getCursorDecl(Cursor);
425 assert(D && "Invalid declaration cursor");
426 if (D->getPCHLevel() > MaxPCHLevel)
427 return false;
428
429 if (D->isImplicit())
430 return false;
431 }
432
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000433 // If we have a range of interest, and this cursor doesn't intersect with it,
434 // we're done.
435 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000436 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000437 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000438 return false;
439 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000440
Douglas Gregorb1373d02010-01-20 20:59:29 +0000441 switch (Visitor(Cursor, Parent, ClientData)) {
442 case CXChildVisit_Break:
443 return true;
444
445 case CXChildVisit_Continue:
446 return false;
447
448 case CXChildVisit_Recurse:
449 return VisitChildren(Cursor);
450 }
451
Douglas Gregorfd643772010-01-25 16:45:46 +0000452 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000453}
454
Douglas Gregor788f5a12010-03-20 00:41:21 +0000455std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
456CursorVisitor::getPreprocessedEntities() {
457 PreprocessingRecord &PPRec
458 = *TU->getPreprocessor().getPreprocessingRecord();
459
460 bool OnlyLocalDecls
461 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
462
463 // There is no region of interest; we have to walk everything.
464 if (RegionOfInterest.isInvalid())
465 return std::make_pair(PPRec.begin(OnlyLocalDecls),
466 PPRec.end(OnlyLocalDecls));
467
468 // Find the file in which the region of interest lands.
469 SourceManager &SM = TU->getSourceManager();
470 std::pair<FileID, unsigned> Begin
471 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
472 std::pair<FileID, unsigned> End
473 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
474
475 // The region of interest spans files; we have to walk everything.
476 if (Begin.first != End.first)
477 return std::make_pair(PPRec.begin(OnlyLocalDecls),
478 PPRec.end(OnlyLocalDecls));
479
480 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
481 = TU->getPreprocessedEntitiesByFile();
482 if (ByFileMap.empty()) {
483 // Build the mapping from files to sets of preprocessed entities.
484 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
485 EEnd = PPRec.end(OnlyLocalDecls);
486 E != EEnd; ++E) {
487 std::pair<FileID, unsigned> P
488 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
489 ByFileMap[P.first].push_back(*E);
490 }
491 }
492
493 return std::make_pair(ByFileMap[Begin.first].begin(),
494 ByFileMap[Begin.first].end());
495}
496
Douglas Gregorb1373d02010-01-20 20:59:29 +0000497/// \brief Visit the children of the given cursor.
498///
499/// \returns true if the visitation should be aborted, false if it
500/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000501bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000502 if (clang_isReference(Cursor.kind)) {
503 // By definition, references have no children.
504 return false;
505 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000506
507 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000508 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000509 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000510
Douglas Gregorb1373d02010-01-20 20:59:29 +0000511 if (clang_isDeclaration(Cursor.kind)) {
512 Decl *D = getCursorDecl(Cursor);
513 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000514 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000515 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000516
Douglas Gregora59e3902010-01-21 23:27:09 +0000517 if (clang_isStatement(Cursor.kind))
518 return Visit(getCursorStmt(Cursor));
519 if (clang_isExpression(Cursor.kind))
520 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000521
Douglas Gregorb1373d02010-01-20 20:59:29 +0000522 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000523 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000524 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
525 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000526 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
527 TLEnd = CXXUnit->top_level_end();
528 TL != TLEnd; ++TL) {
529 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000530 return true;
531 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000532 } else if (VisitDeclContext(
533 CXXUnit->getASTContext().getTranslationUnitDecl()))
534 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000535
Douglas Gregor0396f462010-03-19 05:22:59 +0000536 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000537 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000538 // FIXME: Once we have the ability to deserialize a preprocessing record,
539 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000540 PreprocessingRecord::iterator E, EEnd;
541 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000542 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
543 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
544 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000545
Douglas Gregor0396f462010-03-19 05:22:59 +0000546 continue;
547 }
548
549 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
550 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
551 return true;
552
553 continue;
554 }
555 }
556 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000557 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000558 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000559
Douglas Gregorb1373d02010-01-20 20:59:29 +0000560 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000561 return false;
562}
563
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000564bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000565 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
566 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000567
Ted Kremenek664cffd2010-07-22 11:30:19 +0000568 if (Stmt *Body = B->getBody())
569 return Visit(MakeCXCursor(Body, StmtParent, TU));
570
571 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000572}
573
Douglas Gregorb1373d02010-01-20 20:59:29 +0000574bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000575 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000576 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000577
Ted Kremenek23173d72010-05-18 21:09:07 +0000578 Decl *D = *I;
579 if (D->getLexicalDeclContext() != DC)
580 continue;
581
582 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000583
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000584 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000585 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000586 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000587 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000588
589 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000590 case RangeBefore:
591 // This declaration comes before the region of interest; skip it.
592 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000593
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000594 case RangeAfter:
595 // This declaration comes after the region of interest; we're done.
596 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000597
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000598 case RangeOverlap:
599 // This declaration overlaps the region of interest; visit it.
600 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000601 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000602 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000603
Daniel Dunbard52864b2010-02-14 10:02:57 +0000604 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000605 return true;
606 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000607
Douglas Gregorb1373d02010-01-20 20:59:29 +0000608 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000609}
610
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000611bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
612 llvm_unreachable("Translation units are visited directly by Visit()");
613 return false;
614}
615
616bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
617 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
618 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000619
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000620 return false;
621}
622
623bool CursorVisitor::VisitTagDecl(TagDecl *D) {
624 return VisitDeclContext(D);
625}
626
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000627bool CursorVisitor::VisitClassTemplateSpecializationDecl(
628 ClassTemplateSpecializationDecl *D) {
629 bool ShouldVisitBody = false;
630 switch (D->getSpecializationKind()) {
631 case TSK_Undeclared:
632 case TSK_ImplicitInstantiation:
633 // Nothing to visit
634 return false;
635
636 case TSK_ExplicitInstantiationDeclaration:
637 case TSK_ExplicitInstantiationDefinition:
638 break;
639
640 case TSK_ExplicitSpecialization:
641 ShouldVisitBody = true;
642 break;
643 }
644
645 // Visit the template arguments used in the specialization.
646 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
647 TypeLoc TL = SpecType->getTypeLoc();
648 if (TemplateSpecializationTypeLoc *TSTLoc
649 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
650 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
651 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
652 return true;
653 }
654 }
655
656 if (ShouldVisitBody && VisitCXXRecordDecl(D))
657 return true;
658
659 return false;
660}
661
Douglas Gregor74dbe642010-08-31 19:31:58 +0000662bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
663 ClassTemplatePartialSpecializationDecl *D) {
664 // FIXME: Visit the "outer" template parameter lists on the TagDecl
665 // before visiting these template parameters.
666 if (VisitTemplateParameters(D->getTemplateParameters()))
667 return true;
668
669 // Visit the partial specialization arguments.
670 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
671 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
672 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
673 return true;
674
675 return VisitCXXRecordDecl(D);
676}
677
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000678bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000679 // Visit the default argument.
680 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
681 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
682 if (Visit(DefArg->getTypeLoc()))
683 return true;
684
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000685 return false;
686}
687
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000688bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
689 if (Expr *Init = D->getInitExpr())
690 return Visit(MakeCXCursor(Init, StmtParent, TU));
691 return false;
692}
693
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000694bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
695 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
696 if (Visit(TSInfo->getTypeLoc()))
697 return true;
698
699 return false;
700}
701
Douglas Gregorb1373d02010-01-20 20:59:29 +0000702bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000703 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
704 // Visit the function declaration's syntactic components in the order
705 // written. This requires a bit of work.
706 TypeLoc TL = TSInfo->getTypeLoc();
707 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
708
709 // If we have a function declared directly (without the use of a typedef),
710 // visit just the return type. Otherwise, just visit the function's type
711 // now.
712 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
713 (!FTL && Visit(TL)))
714 return true;
715
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000716 // Visit the nested-name-specifier, if present.
717 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
718 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
719 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000720
721 // Visit the declaration name.
722 if (VisitDeclarationNameInfo(ND->getNameInfo()))
723 return true;
724
725 // FIXME: Visit explicitly-specified template arguments!
726
727 // Visit the function parameters, if we have a function type.
728 if (FTL && VisitFunctionTypeLoc(*FTL, true))
729 return true;
730
731 // FIXME: Attributes?
732 }
733
Douglas Gregora59e3902010-01-21 23:27:09 +0000734 if (ND->isThisDeclarationADefinition() &&
735 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
736 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000737
Douglas Gregorb1373d02010-01-20 20:59:29 +0000738 return false;
739}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000740
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000741bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
742 if (VisitDeclaratorDecl(D))
743 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000744
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000745 if (Expr *BitWidth = D->getBitWidth())
746 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000747
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000748 return false;
749}
750
751bool CursorVisitor::VisitVarDecl(VarDecl *D) {
752 if (VisitDeclaratorDecl(D))
753 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000754
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000755 if (Expr *Init = D->getInit())
756 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000757
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000758 return false;
759}
760
Douglas Gregor84b51d72010-09-01 20:16:53 +0000761bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
762 if (VisitDeclaratorDecl(D))
763 return true;
764
765 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
766 if (Expr *DefArg = D->getDefaultArgument())
767 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
768
769 return false;
770}
771
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000772bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
773 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
774 // before visiting these template parameters.
775 if (VisitTemplateParameters(D->getTemplateParameters()))
776 return true;
777
778 return VisitFunctionDecl(D->getTemplatedDecl());
779}
780
Douglas Gregor39d6f072010-08-31 19:02:00 +0000781bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
782 // FIXME: Visit the "outer" template parameter lists on the TagDecl
783 // before visiting these template parameters.
784 if (VisitTemplateParameters(D->getTemplateParameters()))
785 return true;
786
787 return VisitCXXRecordDecl(D->getTemplatedDecl());
788}
789
Douglas Gregor84b51d72010-09-01 20:16:53 +0000790bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
791 if (VisitTemplateParameters(D->getTemplateParameters()))
792 return true;
793
794 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
795 VisitTemplateArgumentLoc(D->getDefaultArgument()))
796 return true;
797
798 return false;
799}
800
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000801bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000802 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
803 if (Visit(TSInfo->getTypeLoc()))
804 return true;
805
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000806 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000807 PEnd = ND->param_end();
808 P != PEnd; ++P) {
809 if (Visit(MakeCXCursor(*P, TU)))
810 return true;
811 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000812
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000813 if (ND->isThisDeclarationADefinition() &&
814 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
815 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000816
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000817 return false;
818}
819
Douglas Gregora59e3902010-01-21 23:27:09 +0000820bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
821 return VisitDeclContext(D);
822}
823
Douglas Gregorb1373d02010-01-20 20:59:29 +0000824bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000825 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
826 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000827 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000828
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000829 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
830 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
831 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000832 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000833 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000834
Douglas Gregora59e3902010-01-21 23:27:09 +0000835 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000836}
837
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000838bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
839 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
840 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
841 E = PID->protocol_end(); I != E; ++I, ++PL)
842 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
843 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000844
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000845 return VisitObjCContainerDecl(PID);
846}
847
Ted Kremenek23173d72010-05-18 21:09:07 +0000848bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000849 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
850 return true;
851
Ted Kremenek23173d72010-05-18 21:09:07 +0000852 // FIXME: This implements a workaround with @property declarations also being
853 // installed in the DeclContext for the @interface. Eventually this code
854 // should be removed.
855 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
856 if (!CDecl || !CDecl->IsClassExtension())
857 return false;
858
859 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
860 if (!ID)
861 return false;
862
863 IdentifierInfo *PropertyId = PD->getIdentifier();
864 ObjCPropertyDecl *prevDecl =
865 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
866
867 if (!prevDecl)
868 return false;
869
870 // Visit synthesized methods since they will be skipped when visiting
871 // the @interface.
872 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
873 if (MD->isSynthesized())
874 if (Visit(MakeCXCursor(MD, TU)))
875 return true;
876
877 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
878 if (MD->isSynthesized())
879 if (Visit(MakeCXCursor(MD, TU)))
880 return true;
881
882 return false;
883}
884
Douglas Gregorb1373d02010-01-20 20:59:29 +0000885bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000886 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000887 if (D->getSuperClass() &&
888 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000889 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000890 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000891 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000892
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000893 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
894 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
895 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000896 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000897 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000898
Douglas Gregora59e3902010-01-21 23:27:09 +0000899 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000900}
901
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000902bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
903 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000904}
905
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000906bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000907 // 'ID' could be null when dealing with invalid code.
908 if (ObjCInterfaceDecl *ID = D->getClassInterface())
909 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
910 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000911
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000912 return VisitObjCImplDecl(D);
913}
914
915bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
916#if 0
917 // Issue callbacks for super class.
918 // FIXME: No source location information!
919 if (D->getSuperClass() &&
920 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000921 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000922 TU)))
923 return true;
924#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000925
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000926 return VisitObjCImplDecl(D);
927}
928
929bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
930 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
931 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
932 E = D->protocol_end();
933 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000934 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000935 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000936
937 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000938}
939
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000940bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
941 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
942 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
943 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000944
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000945 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000946}
947
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000948bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
949 return VisitDeclContext(D);
950}
951
Douglas Gregor69319002010-08-31 23:48:11 +0000952bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000953 // Visit nested-name-specifier.
954 if (NestedNameSpecifier *Qualifier = D->getQualifier())
955 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
956 return true;
Douglas Gregor69319002010-08-31 23:48:11 +0000957
958 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
959 D->getTargetNameLoc(), TU));
960}
961
Douglas Gregor7e242562010-09-01 19:52:22 +0000962bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000963 // Visit nested-name-specifier.
964 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
965 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
966 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +0000967
968 // FIXME: Provide a multi-reference of some kind for all of the declarations
969 // that the using declaration refers to. We don't have this kind of cursor
970 // yet.
971
972 return VisitDeclarationNameInfo(D->getNameInfo());
973}
974
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000975bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000976 // Visit nested-name-specifier.
977 if (NestedNameSpecifier *Qualifier = D->getQualifier())
978 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
979 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000980
981 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
982 D->getIdentLocation(), TU));
983}
984
Douglas Gregor7e242562010-09-01 19:52:22 +0000985bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000986 // Visit nested-name-specifier.
987 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
988 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
989 return true;
990
Douglas Gregor7e242562010-09-01 19:52:22 +0000991 return VisitDeclarationNameInfo(D->getNameInfo());
992}
993
994bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
995 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000996 // Visit nested-name-specifier.
997 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
998 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
999 return true;
1000
Douglas Gregor7e242562010-09-01 19:52:22 +00001001 return false;
1002}
1003
Douglas Gregor01829d32010-08-31 14:41:23 +00001004bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1005 switch (Name.getName().getNameKind()) {
1006 case clang::DeclarationName::Identifier:
1007 case clang::DeclarationName::CXXLiteralOperatorName:
1008 case clang::DeclarationName::CXXOperatorName:
1009 case clang::DeclarationName::CXXUsingDirective:
1010 return false;
1011
1012 case clang::DeclarationName::CXXConstructorName:
1013 case clang::DeclarationName::CXXDestructorName:
1014 case clang::DeclarationName::CXXConversionFunctionName:
1015 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1016 return Visit(TSInfo->getTypeLoc());
1017 return false;
1018
1019 case clang::DeclarationName::ObjCZeroArgSelector:
1020 case clang::DeclarationName::ObjCOneArgSelector:
1021 case clang::DeclarationName::ObjCMultiArgSelector:
1022 // FIXME: Per-identifier location info?
1023 return false;
1024 }
1025
1026 return false;
1027}
1028
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001029bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1030 SourceRange Range) {
1031 // FIXME: This whole routine is a hack to work around the lack of proper
1032 // source information in nested-name-specifiers (PR5791). Since we do have
1033 // a beginning source location, we can visit the first component of the
1034 // nested-name-specifier, if it's a single-token component.
1035 if (!NNS)
1036 return false;
1037
1038 // Get the first component in the nested-name-specifier.
1039 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1040 NNS = Prefix;
1041
1042 switch (NNS->getKind()) {
1043 case NestedNameSpecifier::Namespace:
1044 // FIXME: The token at this source location might actually have been a
1045 // namespace alias, but we don't model that. Lame!
1046 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1047 TU));
1048
1049 case NestedNameSpecifier::TypeSpec: {
1050 // If the type has a form where we know that the beginning of the source
1051 // range matches up with a reference cursor. Visit the appropriate reference
1052 // cursor.
1053 Type *T = NNS->getAsType();
1054 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1055 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1056 if (const TagType *Tag = dyn_cast<TagType>(T))
1057 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1058 if (const TemplateSpecializationType *TST
1059 = dyn_cast<TemplateSpecializationType>(T))
1060 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1061 break;
1062 }
1063
1064 case NestedNameSpecifier::TypeSpecWithTemplate:
1065 case NestedNameSpecifier::Global:
1066 case NestedNameSpecifier::Identifier:
1067 break;
1068 }
1069
1070 return false;
1071}
1072
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001073bool CursorVisitor::VisitTemplateParameters(
1074 const TemplateParameterList *Params) {
1075 if (!Params)
1076 return false;
1077
1078 for (TemplateParameterList::const_iterator P = Params->begin(),
1079 PEnd = Params->end();
1080 P != PEnd; ++P) {
1081 if (Visit(MakeCXCursor(*P, TU)))
1082 return true;
1083 }
1084
1085 return false;
1086}
1087
Douglas Gregor0b36e612010-08-31 20:37:03 +00001088bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1089 switch (Name.getKind()) {
1090 case TemplateName::Template:
1091 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1092
1093 case TemplateName::OverloadedTemplate:
1094 // FIXME: We need a way to return multiple lookup results in a single
1095 // cursor.
1096 return false;
1097
1098 case TemplateName::DependentTemplate:
1099 // FIXME: Visit nested-name-specifier.
1100 return false;
1101
1102 case TemplateName::QualifiedTemplate:
1103 // FIXME: Visit nested-name-specifier.
1104 return Visit(MakeCursorTemplateRef(
1105 Name.getAsQualifiedTemplateName()->getDecl(),
1106 Loc, TU));
1107 }
1108
1109 return false;
1110}
1111
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001112bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1113 switch (TAL.getArgument().getKind()) {
1114 case TemplateArgument::Null:
1115 case TemplateArgument::Integral:
1116 return false;
1117
1118 case TemplateArgument::Pack:
1119 // FIXME: Implement when variadic templates come along.
1120 return false;
1121
1122 case TemplateArgument::Type:
1123 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1124 return Visit(TSInfo->getTypeLoc());
1125 return false;
1126
1127 case TemplateArgument::Declaration:
1128 if (Expr *E = TAL.getSourceDeclExpression())
1129 return Visit(MakeCXCursor(E, StmtParent, TU));
1130 return false;
1131
1132 case TemplateArgument::Expression:
1133 if (Expr *E = TAL.getSourceExpression())
1134 return Visit(MakeCXCursor(E, StmtParent, TU));
1135 return false;
1136
1137 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001138 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1139 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001140 }
1141
1142 return false;
1143}
1144
Ted Kremeneka0536d82010-05-07 01:04:29 +00001145bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1146 return VisitDeclContext(D);
1147}
1148
Douglas Gregor01829d32010-08-31 14:41:23 +00001149bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1150 return Visit(TL.getUnqualifiedLoc());
1151}
1152
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001153bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1154 ASTContext &Context = TU->getASTContext();
1155
1156 // Some builtin types (such as Objective-C's "id", "sel", and
1157 // "Class") have associated declarations. Create cursors for those.
1158 QualType VisitType;
1159 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001160 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001161 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001162 case BuiltinType::Char_U:
1163 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001164 case BuiltinType::Char16:
1165 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001166 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001167 case BuiltinType::UInt:
1168 case BuiltinType::ULong:
1169 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001170 case BuiltinType::UInt128:
1171 case BuiltinType::Char_S:
1172 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001173 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001174 case BuiltinType::Short:
1175 case BuiltinType::Int:
1176 case BuiltinType::Long:
1177 case BuiltinType::LongLong:
1178 case BuiltinType::Int128:
1179 case BuiltinType::Float:
1180 case BuiltinType::Double:
1181 case BuiltinType::LongDouble:
1182 case BuiltinType::NullPtr:
1183 case BuiltinType::Overload:
1184 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001185 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001186
1187 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001188 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001189
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001190 case BuiltinType::ObjCId:
1191 VisitType = Context.getObjCIdType();
1192 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001193
1194 case BuiltinType::ObjCClass:
1195 VisitType = Context.getObjCClassType();
1196 break;
1197
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001198 case BuiltinType::ObjCSel:
1199 VisitType = Context.getObjCSelType();
1200 break;
1201 }
1202
1203 if (!VisitType.isNull()) {
1204 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001205 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001206 TU));
1207 }
1208
1209 return false;
1210}
1211
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001212bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1213 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1214}
1215
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001216bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1217 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1218}
1219
1220bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1221 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1222}
1223
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001224bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1225 // FIXME: We can't visit the template template parameter, but there's
1226 // no context information with which we can match up the depth/index in the
1227 // type to the appropriate
1228 return false;
1229}
1230
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001231bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1232 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1233 return true;
1234
John McCallc12c5bb2010-05-15 11:32:37 +00001235 return false;
1236}
1237
1238bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1239 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1240 return true;
1241
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001242 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1243 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1244 TU)))
1245 return true;
1246 }
1247
1248 return false;
1249}
1250
1251bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001252 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001253}
1254
1255bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1256 return Visit(TL.getPointeeLoc());
1257}
1258
1259bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1260 return Visit(TL.getPointeeLoc());
1261}
1262
1263bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1264 return Visit(TL.getPointeeLoc());
1265}
1266
1267bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001268 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001269}
1270
1271bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001272 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001273}
1274
Douglas Gregor01829d32010-08-31 14:41:23 +00001275bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1276 bool SkipResultType) {
1277 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001278 return true;
1279
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001280 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001281 if (Decl *D = TL.getArg(I))
1282 if (Visit(MakeCXCursor(D, TU)))
1283 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001284
1285 return false;
1286}
1287
1288bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1289 if (Visit(TL.getElementLoc()))
1290 return true;
1291
1292 if (Expr *Size = TL.getSizeExpr())
1293 return Visit(MakeCXCursor(Size, StmtParent, TU));
1294
1295 return false;
1296}
1297
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001298bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1299 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001300 // Visit the template name.
1301 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1302 TL.getTemplateNameLoc()))
1303 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001304
1305 // Visit the template arguments.
1306 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1307 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1308 return true;
1309
1310 return false;
1311}
1312
Douglas Gregor2332c112010-01-21 20:48:56 +00001313bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1314 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1315}
1316
1317bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1318 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1319 return Visit(TSInfo->getTypeLoc());
1320
1321 return false;
1322}
1323
Douglas Gregora59e3902010-01-21 23:27:09 +00001324bool CursorVisitor::VisitStmt(Stmt *S) {
1325 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1326 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001327 if (Stmt *C = *Child)
1328 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1329 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001330 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001331
Douglas Gregora59e3902010-01-21 23:27:09 +00001332 return false;
1333}
1334
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001335bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1336 // Specially handle CaseStmts because they can be nested, e.g.:
1337 //
1338 // case 1:
1339 // case 2:
1340 //
1341 // In this case the second CaseStmt is the child of the first. Walking
1342 // these recursively can blow out the stack.
1343 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1344 while (true) {
1345 // Set the Parent field to Cursor, then back to its old value once we're
1346 // done.
1347 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1348
1349 if (Stmt *LHS = S->getLHS())
1350 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1351 return true;
1352 if (Stmt *RHS = S->getRHS())
1353 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1354 return true;
1355 if (Stmt *SubStmt = S->getSubStmt()) {
1356 if (!isa<CaseStmt>(SubStmt))
1357 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1358
1359 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1360 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1361 Cursor = MakeCXCursor(CS, StmtParent, TU);
1362 if (RegionOfInterest.isValid()) {
1363 SourceRange Range = CS->getSourceRange();
1364 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1365 return false;
1366 }
1367
1368 switch (Visitor(Cursor, Parent, ClientData)) {
1369 case CXChildVisit_Break: return true;
1370 case CXChildVisit_Continue: return false;
1371 case CXChildVisit_Recurse:
1372 // Perform tail-recursion manually.
1373 S = CS;
1374 continue;
1375 }
1376 }
1377 return false;
1378 }
1379}
1380
Douglas Gregora59e3902010-01-21 23:27:09 +00001381bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1382 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1383 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001384 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001385 return true;
1386 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001387
Douglas Gregora59e3902010-01-21 23:27:09 +00001388 return false;
1389}
1390
Douglas Gregorf5bab412010-01-22 01:00:11 +00001391bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1392 if (VarDecl *Var = S->getConditionVariable()) {
1393 if (Visit(MakeCXCursor(Var, TU)))
1394 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001395 }
1396
Douglas Gregor263b47b2010-01-25 16:12:32 +00001397 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1398 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001399 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1400 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001401 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1402 return true;
1403
1404 return false;
1405}
1406
1407bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1408 if (VarDecl *Var = S->getConditionVariable()) {
1409 if (Visit(MakeCXCursor(Var, TU)))
1410 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001411 }
1412
Douglas Gregor263b47b2010-01-25 16:12:32 +00001413 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1414 return true;
1415 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1416 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001417
Douglas Gregor263b47b2010-01-25 16:12:32 +00001418 return false;
1419}
1420
1421bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1422 if (VarDecl *Var = S->getConditionVariable()) {
1423 if (Visit(MakeCXCursor(Var, TU)))
1424 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001425 }
1426
Douglas Gregor263b47b2010-01-25 16:12:32 +00001427 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1428 return true;
1429 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001430 return true;
1431
Douglas Gregor263b47b2010-01-25 16:12:32 +00001432 return false;
1433}
1434
1435bool CursorVisitor::VisitForStmt(ForStmt *S) {
1436 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1437 return true;
1438 if (VarDecl *Var = S->getConditionVariable()) {
1439 if (Visit(MakeCXCursor(Var, TU)))
1440 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001441 }
1442
Douglas Gregor263b47b2010-01-25 16:12:32 +00001443 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1444 return true;
1445 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1446 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001447 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1448 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001449
Douglas Gregorf5bab412010-01-22 01:00:11 +00001450 return false;
1451}
1452
Douglas Gregor8947a752010-09-02 20:35:02 +00001453bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1454 // Visit nested-name-specifier, if present.
1455 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1456 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1457 return true;
1458
1459 // Visit declaration name.
1460 if (VisitDeclarationNameInfo(E->getNameInfo()))
1461 return true;
1462
1463 // Visit explicitly-specified template arguments.
1464 if (E->hasExplicitTemplateArgs()) {
1465 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1466 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1467 *ArgEnd = Arg + Args.NumTemplateArgs;
1468 Arg != ArgEnd; ++Arg)
1469 if (VisitTemplateArgumentLoc(*Arg))
1470 return true;
1471 }
1472
1473 return false;
1474}
1475
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001476bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1477 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1478 return true;
1479
1480 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1481 return true;
1482
1483 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1484 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1485 return true;
1486
1487 return false;
1488}
1489
Ted Kremenek3064ef92010-08-27 21:34:58 +00001490bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1491 if (D->isDefinition()) {
1492 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1493 E = D->bases_end(); I != E; ++I) {
1494 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1495 return true;
1496 }
1497 }
1498
1499 return VisitTagDecl(D);
1500}
1501
1502
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001503bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1504 return Visit(B->getBlockDecl());
1505}
1506
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001507bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1508 // FIXME: Visit fields as well?
1509 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1510 return true;
1511
1512 return VisitExpr(E);
1513}
1514
Douglas Gregor336fd812010-01-23 00:40:08 +00001515bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1516 if (E->isArgumentType()) {
1517 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1518 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001519
Douglas Gregor336fd812010-01-23 00:40:08 +00001520 return false;
1521 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001522
Douglas Gregor336fd812010-01-23 00:40:08 +00001523 return VisitExpr(E);
1524}
1525
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001526bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1527 // Visit the base expression.
1528 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1529 return true;
1530
1531 // Visit the nested-name-specifier
1532 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1533 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1534 return true;
1535
1536 // Visit the declaration name.
1537 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1538 return true;
1539
1540 // Visit the explicitly-specified template arguments, if any.
1541 if (E->hasExplicitTemplateArgs()) {
1542 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1543 *ArgEnd = Arg + E->getNumTemplateArgs();
1544 Arg != ArgEnd;
1545 ++Arg) {
1546 if (VisitTemplateArgumentLoc(*Arg))
1547 return true;
1548 }
1549 }
1550
1551 return false;
1552}
1553
Douglas Gregor336fd812010-01-23 00:40:08 +00001554bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1555 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1556 if (Visit(TSInfo->getTypeLoc()))
1557 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001558
Douglas Gregor336fd812010-01-23 00:40:08 +00001559 return VisitCastExpr(E);
1560}
1561
1562bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1563 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1564 if (Visit(TSInfo->getTypeLoc()))
1565 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001566
Douglas Gregor336fd812010-01-23 00:40:08 +00001567 return VisitExpr(E);
1568}
1569
Douglas Gregor648220e2010-08-10 15:02:34 +00001570bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1571 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1572 Visit(E->getArgTInfo2()->getTypeLoc());
1573}
1574
1575bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1576 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1577 return true;
1578
1579 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1580}
1581
Douglas Gregor94802292010-09-02 21:20:16 +00001582bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1583 if (E->isTypeOperand()) {
1584 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1585 return Visit(TSInfo->getTypeLoc());
1586
1587 return false;
1588 }
1589
1590 return VisitExpr(E);
1591}
1592
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001593bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1594 // Visit placement arguments.
1595 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1596 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1597 return true;
1598
1599 // Visit the allocated type.
1600 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1601 if (Visit(TSInfo->getTypeLoc()))
1602 return true;
1603
1604 // Visit the array size, if any.
1605 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1606 return true;
1607
1608 // Visit the initializer or constructor arguments.
1609 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1610 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1611 return true;
1612
1613 return false;
1614}
1615
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001616bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1617 // Visit base expression.
1618 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1619 return true;
1620
1621 // Visit the nested-name-specifier.
1622 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1623 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1624 return true;
1625
1626 // Visit the scope type that looks disturbingly like the nested-name-specifier
1627 // but isn't.
1628 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1629 if (Visit(TSInfo->getTypeLoc()))
1630 return true;
1631
1632 // Visit the name of the type being destroyed.
1633 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1634 if (Visit(TSInfo->getTypeLoc()))
1635 return true;
1636
1637 return false;
1638}
1639
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001640bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001641 // Visit the nested-name-specifier.
1642 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1643 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1644 return true;
1645
1646 // Visit the declaration name.
1647 if (VisitDeclarationNameInfo(E->getNameInfo()))
1648 return true;
1649
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001650 // Visit the explicitly-specified template arguments.
1651 if (const ExplicitTemplateArgumentList *ArgList
1652 = E->getOptionalExplicitTemplateArgs()) {
1653 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1654 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1655 Arg != ArgEnd; ++Arg) {
1656 if (VisitTemplateArgumentLoc(*Arg))
1657 return true;
1658 }
1659 }
1660
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001661 // FIXME: We don't have a way to visit all of the declarations referenced
1662 // here.
1663 return false;
1664}
1665
Douglas Gregorbfebed22010-09-03 17:24:10 +00001666bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1667 DependentScopeDeclRefExpr *E) {
1668 // Visit the nested-name-specifier.
1669 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1670 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1671 return true;
1672
1673 // Visit the declaration name.
1674 if (VisitDeclarationNameInfo(E->getNameInfo()))
1675 return true;
1676
1677 // Visit the explicitly-specified template arguments.
1678 if (const ExplicitTemplateArgumentList *ArgList
1679 = E->getOptionalExplicitTemplateArgs()) {
1680 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1681 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1682 Arg != ArgEnd; ++Arg) {
1683 if (VisitTemplateArgumentLoc(*Arg))
1684 return true;
1685 }
1686 }
1687
1688 return false;
1689}
1690
Douglas Gregor25d63622010-09-03 17:35:34 +00001691bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1692 CXXDependentScopeMemberExpr *E) {
1693 // Visit the base expression, if there is one.
1694 if (!E->isImplicitAccess() &&
1695 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1696 return true;
1697
1698 // Visit the nested-name-specifier.
1699 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1700 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1701 return true;
1702
1703 // Visit the declaration name.
1704 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1705 return true;
1706
1707 // Visit the explicitly-specified template arguments.
1708 if (const ExplicitTemplateArgumentList *ArgList
1709 = E->getOptionalExplicitTemplateArgs()) {
1710 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1711 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1712 Arg != ArgEnd; ++Arg) {
1713 if (VisitTemplateArgumentLoc(*Arg))
1714 return true;
1715 }
1716 }
1717
1718 return false;
1719}
1720
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001721bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1722 // Visit the base expression, if there is one.
1723 if (!E->isImplicitAccess() &&
1724 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1725 return true;
1726
1727 return VisitOverloadExpr(E);
1728}
Douglas Gregor25d63622010-09-03 17:35:34 +00001729
Douglas Gregorc2350e52010-03-08 16:40:19 +00001730bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001731 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1732 if (Visit(TSInfo->getTypeLoc()))
1733 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001734
1735 return VisitExpr(E);
1736}
1737
Douglas Gregor81d34662010-04-20 15:39:42 +00001738bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1739 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1740}
1741
1742
Ted Kremenek09dfa372010-02-18 05:46:33 +00001743bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001744 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1745 i != e; ++i)
1746 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001747 return true;
1748
1749 return false;
1750}
1751
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001752extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001753CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1754 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001755 // We use crash recovery to make some of our APIs more reliable, implicitly
1756 // enable it.
1757 llvm::CrashRecoveryContext::Enable();
1758
Douglas Gregora030b7c2010-01-22 20:35:53 +00001759 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001760 if (excludeDeclarationsFromPCH)
1761 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001762 if (displayDiagnostics)
1763 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001764 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001765}
1766
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001767void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001768 if (CIdx)
1769 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001770 if (getenv("LIBCLANG_TIMING"))
1771 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001772}
1773
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001774void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001775 if (CIdx) {
1776 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1777 CXXIdx->setUseExternalASTGeneration(value);
1778 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001779}
1780
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001781CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001782 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001783 if (!CIdx)
1784 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001785
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001786 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001787
Douglas Gregor28019772010-04-05 23:52:57 +00001788 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001789 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001790 CXXIdx->getOnlyLocalDecls(),
1791 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001792}
1793
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001794unsigned clang_defaultEditingTranslationUnitOptions() {
1795 return CXTranslationUnit_PrecompiledPreamble;
1796}
1797
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001798CXTranslationUnit
1799clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1800 const char *source_filename,
1801 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001802 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001803 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001804 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001805 return clang_parseTranslationUnit(CIdx, source_filename,
1806 command_line_args, num_command_line_args,
1807 unsaved_files, num_unsaved_files,
1808 CXTranslationUnit_DetailedPreprocessingRecord);
1809}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001810
1811struct ParseTranslationUnitInfo {
1812 CXIndex CIdx;
1813 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001814 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001815 int num_command_line_args;
1816 struct CXUnsavedFile *unsaved_files;
1817 unsigned num_unsaved_files;
1818 unsigned options;
1819 CXTranslationUnit result;
1820};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001821static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001822 ParseTranslationUnitInfo *PTUI =
1823 static_cast<ParseTranslationUnitInfo*>(UserData);
1824 CXIndex CIdx = PTUI->CIdx;
1825 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001826 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001827 int num_command_line_args = PTUI->num_command_line_args;
1828 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1829 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1830 unsigned options = PTUI->options;
1831 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001832
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001833 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001834 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001835
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001836 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1837
Douglas Gregor44c181a2010-07-23 00:33:23 +00001838 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001839 bool CompleteTranslationUnit
1840 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001841 bool CacheCodeCompetionResults
1842 = options & CXTranslationUnit_CacheCompletionResults;
1843
Douglas Gregor5352ac02010-01-28 00:27:43 +00001844 // Configure the diagnostics.
1845 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001846 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1847 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001848
Douglas Gregor4db64a42010-01-23 00:14:00 +00001849 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1850 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001851 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001852 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001853 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001854 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1855 Buffer));
1856 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001857
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001858 if (!CXXIdx->getUseExternalASTGeneration()) {
1859 llvm::SmallVector<const char *, 16> Args;
1860
1861 // The 'source_filename' argument is optional. If the caller does not
1862 // specify it then it is assumed that the source file is specified
1863 // in the actual argument list.
1864 if (source_filename)
1865 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001866
1867 // Since the Clang C library is primarily used by batch tools dealing with
1868 // (often very broken) source code, where spell-checking can have a
1869 // significant negative impact on performance (particularly when
1870 // precompiled headers are involved), we disable it by default.
1871 // Note that we place this argument early in the list, so that it can be
1872 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001873 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001874
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001875 Args.insert(Args.end(), command_line_args,
1876 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001877
Douglas Gregor44c181a2010-07-23 00:33:23 +00001878 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001879 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1880 Args.push_back("-Xclang");
1881 Args.push_back("-detailed-preprocessing-record");
1882 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001883
Douglas Gregor5352ac02010-01-28 00:27:43 +00001884 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001885
Ted Kremenek29b72842010-01-07 22:49:05 +00001886#ifdef USE_CRASHTRACER
1887 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001888#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001889
Daniel Dunbar94220972009-12-05 02:17:18 +00001890 llvm::OwningPtr<ASTUnit> Unit(
1891 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001892 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001893 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001894 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001895 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001896 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001897 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001898 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001899 CompleteTranslationUnit,
1900 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001901
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001902 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001903 // Make sure to check that 'Unit' is non-NULL.
1904 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001905 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1906 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001907 D != DEnd; ++D) {
1908 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001909 CXString Msg = clang_formatDiagnostic(&Diag,
1910 clang_defaultDiagnosticDisplayOptions());
1911 fprintf(stderr, "%s\n", clang_getCString(Msg));
1912 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001913 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001914#ifdef LLVM_ON_WIN32
1915 // On Windows, force a flush, since there may be multiple copies of
1916 // stderr and stdout in the file system, all with different buffers
1917 // but writing to the same device.
1918 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001919#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001920 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001921 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001922
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001923 PTUI->result = Unit.take();
1924 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001925 }
1926
Ted Kremenek139ba862009-10-22 00:03:57 +00001927 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001928 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001929
Ted Kremenek139ba862009-10-22 00:03:57 +00001930 // First add the complete path to the 'clang' executable.
1931 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001932 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001933
Ted Kremenek139ba862009-10-22 00:03:57 +00001934 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001935 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001936
Ted Kremenek139ba862009-10-22 00:03:57 +00001937 // The 'source_filename' argument is optional. If the caller does not
1938 // specify it then it is assumed that the source file is specified
1939 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001940 if (source_filename)
1941 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001942
Steve Naroff37b5ac22009-10-15 20:50:09 +00001943 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001944 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001945 char astTmpFile[L_tmpnam];
1946 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001947
1948 // Since the Clang C library is primarily used by batch tools dealing with
1949 // (often very broken) source code, where spell-checking can have a
1950 // significant negative impact on performance (particularly when
1951 // precompiled headers are involved), we disable it by default.
1952 // Note that we place this argument early in the list, so that it can be
1953 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001954 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001955
Douglas Gregor4db64a42010-01-23 00:14:00 +00001956 // Remap any unsaved files to temporary files.
1957 std::vector<llvm::sys::Path> TemporaryFiles;
1958 std::vector<std::string> RemapArgs;
1959 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001960 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001961
Douglas Gregor4db64a42010-01-23 00:14:00 +00001962 // The pointers into the elements of RemapArgs are stable because we
1963 // won't be adding anything to RemapArgs after this point.
1964 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1965 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001966
Ted Kremenek139ba862009-10-22 00:03:57 +00001967 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1968 for (int i = 0; i < num_command_line_args; ++i)
1969 if (const char *arg = command_line_args[i]) {
1970 if (strcmp(arg, "-o") == 0) {
1971 ++i; // Also skip the matching argument.
1972 continue;
1973 }
1974 if (strcmp(arg, "-emit-ast") == 0 ||
1975 strcmp(arg, "-c") == 0 ||
1976 strcmp(arg, "-fsyntax-only") == 0) {
1977 continue;
1978 }
1979
1980 // Keep the argument.
1981 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001982 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001983
Douglas Gregord93256e2010-01-28 06:00:51 +00001984 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001985 char tmpFileResults[L_tmpnam];
1986 char *tmpResultsFileName = tmpnam(tmpFileResults);
1987 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001988 TemporaryFiles.push_back(DiagnosticsFile);
1989 argv.push_back("-fdiagnostics-binary");
1990
Douglas Gregor44c181a2010-07-23 00:33:23 +00001991 // Do we need the detailed preprocessing record?
1992 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1993 argv.push_back("-Xclang");
1994 argv.push_back("-detailed-preprocessing-record");
1995 }
1996
Ted Kremenek139ba862009-10-22 00:03:57 +00001997 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001998 argv.push_back(NULL);
1999
Ted Kremenekfeb15e32009-10-26 22:14:08 +00002000 // Invoke 'clang'.
2001 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
2002 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00002003 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00002004 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
2005 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00002006 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002007 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00002008 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002009
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002010 if (!ErrMsg.empty()) {
2011 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00002012 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002013 I != E; ++I) {
2014 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00002015 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002016 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00002017 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002018
Daniel Dunbar32141c82010-02-23 20:23:45 +00002019 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00002020 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00002021
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002022 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002023 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00002024 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00002025 RemappedFiles.size(),
2026 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00002027 if (ATU) {
2028 LoadSerializedDiagnostics(DiagnosticsFile,
2029 num_unsaved_files, unsaved_files,
2030 ATU->getFileManager(),
2031 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00002032 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002033 } else if (CXXIdx->getDisplayDiagnostics()) {
2034 // We failed to load the ASTUnit, but we can still deserialize the
2035 // diagnostics and emit them.
2036 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00002037 Diagnostic Diag;
2038 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002039 // FIXME: Faked LangOpts!
2040 LangOptions LangOpts;
2041 llvm::SmallVector<StoredDiagnostic, 4> Diags;
2042 LoadSerializedDiagnostics(DiagnosticsFile,
2043 num_unsaved_files, unsaved_files,
2044 FileMgr, SourceMgr, Diags);
2045 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
2046 DEnd = Diags.end();
2047 D != DEnd; ++D) {
2048 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00002049 CXString Msg = clang_formatDiagnostic(&Diag,
2050 clang_defaultDiagnosticDisplayOptions());
2051 fprintf(stderr, "%s\n", clang_getCString(Msg));
2052 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002053 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002054
2055#ifdef LLVM_ON_WIN32
2056 // On Windows, force a flush, since there may be multiple copies of
2057 // stderr and stdout in the file system, all with different buffers
2058 // but writing to the same device.
2059 fflush(stderr);
2060#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00002061 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002062
Douglas Gregor313e26c2010-02-18 23:35:40 +00002063 if (ATU) {
2064 // Make the translation unit responsible for destroying all temporary files.
2065 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2066 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002067 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00002068 } else {
2069 // Destroy all of the temporary files now; they can't be referenced any
2070 // longer.
2071 llvm::sys::Path(astTmpFile).eraseFromDisk();
2072 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2073 TemporaryFiles[i].eraseFromDisk();
2074 }
2075
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002076 PTUI->result = ATU;
2077}
2078CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2079 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002080 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002081 int num_command_line_args,
2082 struct CXUnsavedFile *unsaved_files,
2083 unsigned num_unsaved_files,
2084 unsigned options) {
2085 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2086 num_command_line_args, unsaved_files, num_unsaved_files,
2087 options, 0 };
2088 llvm::CrashRecoveryContext CRC;
2089
2090 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002091 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2092 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2093 fprintf(stderr, " 'command_line_args' : [");
2094 for (int i = 0; i != num_command_line_args; ++i) {
2095 if (i)
2096 fprintf(stderr, ", ");
2097 fprintf(stderr, "'%s'", command_line_args[i]);
2098 }
2099 fprintf(stderr, "],\n");
2100 fprintf(stderr, " 'unsaved_files' : [");
2101 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2102 if (i)
2103 fprintf(stderr, ", ");
2104 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2105 unsaved_files[i].Length);
2106 }
2107 fprintf(stderr, "],\n");
2108 fprintf(stderr, " 'options' : %d,\n", options);
2109 fprintf(stderr, "}\n");
2110
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002111 return 0;
2112 }
2113
2114 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002115}
2116
Douglas Gregor19998442010-08-13 15:35:05 +00002117unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2118 return CXSaveTranslationUnit_None;
2119}
2120
2121int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2122 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002123 if (!TU)
2124 return 1;
2125
2126 return static_cast<ASTUnit *>(TU)->Save(FileName);
2127}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002128
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002129void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002130 if (CTUnit) {
2131 // If the translation unit has been marked as unsafe to free, just discard
2132 // it.
2133 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2134 return;
2135
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002136 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002137 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002138}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002139
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002140unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2141 return CXReparse_None;
2142}
2143
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002144struct ReparseTranslationUnitInfo {
2145 CXTranslationUnit TU;
2146 unsigned num_unsaved_files;
2147 struct CXUnsavedFile *unsaved_files;
2148 unsigned options;
2149 int result;
2150};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002151static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002152 ReparseTranslationUnitInfo *RTUI =
2153 static_cast<ReparseTranslationUnitInfo*>(UserData);
2154 CXTranslationUnit TU = RTUI->TU;
2155 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2156 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2157 unsigned options = RTUI->options;
2158 (void) options;
2159 RTUI->result = 1;
2160
Douglas Gregorabc563f2010-07-19 21:46:24 +00002161 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002162 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002163
2164 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2165 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2166 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2167 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002168 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002169 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2170 Buffer));
2171 }
2172
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002173 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
2174 RemappedFiles.size()))
2175 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002176}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002177int clang_reparseTranslationUnit(CXTranslationUnit TU,
2178 unsigned num_unsaved_files,
2179 struct CXUnsavedFile *unsaved_files,
2180 unsigned options) {
2181 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2182 options, 0 };
2183 llvm::CrashRecoveryContext CRC;
2184
2185 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002186 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002187 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2188 return 1;
2189 }
2190
2191 return RTUI.result;
2192}
2193
Douglas Gregordf95a132010-08-09 20:45:32 +00002194
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002195CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002196 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002197 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002198
Steve Naroff77accc12009-09-03 18:19:54 +00002199 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002200 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002201}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002202
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002203CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002204 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002205 return Result;
2206}
2207
Ted Kremenekfb480492010-01-13 21:46:36 +00002208} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002209
Ted Kremenekfb480492010-01-13 21:46:36 +00002210//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002211// CXSourceLocation and CXSourceRange Operations.
2212//===----------------------------------------------------------------------===//
2213
Douglas Gregorb9790342010-01-22 21:44:22 +00002214extern "C" {
2215CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002216 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002217 return Result;
2218}
2219
2220unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002221 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2222 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2223 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002224}
2225
2226CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2227 CXFile file,
2228 unsigned line,
2229 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002230 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002231 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002232
Douglas Gregorb9790342010-01-22 21:44:22 +00002233 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2234 SourceLocation SLoc
2235 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002236 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002237 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002238
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002239 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002240}
2241
Douglas Gregor5352ac02010-01-28 00:27:43 +00002242CXSourceRange clang_getNullRange() {
2243 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2244 return Result;
2245}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002246
Douglas Gregor5352ac02010-01-28 00:27:43 +00002247CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2248 if (begin.ptr_data[0] != end.ptr_data[0] ||
2249 begin.ptr_data[1] != end.ptr_data[1])
2250 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002251
2252 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002253 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002254 return Result;
2255}
2256
Douglas Gregor46766dc2010-01-26 19:19:08 +00002257void clang_getInstantiationLocation(CXSourceLocation location,
2258 CXFile *file,
2259 unsigned *line,
2260 unsigned *column,
2261 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002262 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2263
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002264 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002265 if (file)
2266 *file = 0;
2267 if (line)
2268 *line = 0;
2269 if (column)
2270 *column = 0;
2271 if (offset)
2272 *offset = 0;
2273 return;
2274 }
2275
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002276 const SourceManager &SM =
2277 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002278 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002279
2280 if (file)
2281 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2282 if (line)
2283 *line = SM.getInstantiationLineNumber(InstLoc);
2284 if (column)
2285 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002286 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002287 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002288}
2289
Douglas Gregor1db19de2010-01-19 21:36:55 +00002290CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002291 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002292 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002293 return Result;
2294}
2295
2296CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002297 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002298 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002299 return Result;
2300}
2301
Douglas Gregorb9790342010-01-22 21:44:22 +00002302} // end: extern "C"
2303
Douglas Gregor1db19de2010-01-19 21:36:55 +00002304//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002305// CXFile Operations.
2306//===----------------------------------------------------------------------===//
2307
2308extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002309CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002310 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002311 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002312
Steve Naroff88145032009-10-27 14:35:18 +00002313 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002314 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002315}
2316
2317time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002318 if (!SFile)
2319 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002320
Steve Naroff88145032009-10-27 14:35:18 +00002321 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2322 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002323}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002324
Douglas Gregorb9790342010-01-22 21:44:22 +00002325CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2326 if (!tu)
2327 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002328
Douglas Gregorb9790342010-01-22 21:44:22 +00002329 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002330
Douglas Gregorb9790342010-01-22 21:44:22 +00002331 FileManager &FMgr = CXXUnit->getFileManager();
2332 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2333 return const_cast<FileEntry *>(File);
2334}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002335
Ted Kremenekfb480492010-01-13 21:46:36 +00002336} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002337
Ted Kremenekfb480492010-01-13 21:46:36 +00002338//===----------------------------------------------------------------------===//
2339// CXCursor Operations.
2340//===----------------------------------------------------------------------===//
2341
Ted Kremenekfb480492010-01-13 21:46:36 +00002342static Decl *getDeclFromExpr(Stmt *E) {
2343 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2344 return RefExpr->getDecl();
2345 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2346 return ME->getMemberDecl();
2347 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2348 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002349
Ted Kremenekfb480492010-01-13 21:46:36 +00002350 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2351 return getDeclFromExpr(CE->getCallee());
2352 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2353 return getDeclFromExpr(CE->getSubExpr());
2354 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2355 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002356
Ted Kremenekfb480492010-01-13 21:46:36 +00002357 return 0;
2358}
2359
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002360static SourceLocation getLocationFromExpr(Expr *E) {
2361 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2362 return /*FIXME:*/Msg->getLeftLoc();
2363 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2364 return DRE->getLocation();
2365 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2366 return Member->getMemberLoc();
2367 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2368 return Ivar->getLocation();
2369 return E->getLocStart();
2370}
2371
Ted Kremenekfb480492010-01-13 21:46:36 +00002372extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002373
2374unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002375 CXCursorVisitor visitor,
2376 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002377 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002378
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002379 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2380 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002381 return CursorVis.VisitChildren(parent);
2382}
2383
Douglas Gregor78205d42010-01-20 21:45:58 +00002384static CXString getDeclSpelling(Decl *D) {
2385 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2386 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002387 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002388
Douglas Gregor78205d42010-01-20 21:45:58 +00002389 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002390 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002391
Douglas Gregor78205d42010-01-20 21:45:58 +00002392 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2393 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2394 // and returns different names. NamedDecl returns the class name and
2395 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002396 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002397
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002398 if (isa<UsingDirectiveDecl>(D))
2399 return createCXString("");
2400
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002401 llvm::SmallString<1024> S;
2402 llvm::raw_svector_ostream os(S);
2403 ND->printName(os);
2404
2405 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002406}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002407
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002408CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002409 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002410 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002411
Steve Narofff334b4e2009-09-02 18:26:48 +00002412 if (clang_isReference(C.kind)) {
2413 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002414 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002415 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002416 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002417 }
2418 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002419 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002420 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002421 }
2422 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002423 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002424 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002425 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002426 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002427 case CXCursor_CXXBaseSpecifier: {
2428 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2429 return createCXString(B->getType().getAsString());
2430 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002431 case CXCursor_TypeRef: {
2432 TypeDecl *Type = getCursorTypeRef(C).first;
2433 assert(Type && "Missing type decl");
2434
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002435 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2436 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002437 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002438 case CXCursor_TemplateRef: {
2439 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002440 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002441
2442 return createCXString(Template->getNameAsString());
2443 }
Douglas Gregor69319002010-08-31 23:48:11 +00002444
2445 case CXCursor_NamespaceRef: {
2446 NamedDecl *NS = getCursorNamespaceRef(C).first;
2447 assert(NS && "Missing namespace decl");
2448
2449 return createCXString(NS->getNameAsString());
2450 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002451
Daniel Dunbaracca7252009-11-30 20:42:49 +00002452 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002453 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002454 }
2455 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002456
2457 if (clang_isExpression(C.kind)) {
2458 Decl *D = getDeclFromExpr(getCursorExpr(C));
2459 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002460 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002461 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002462 }
2463
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002464 if (C.kind == CXCursor_MacroInstantiation)
2465 return createCXString(getCursorMacroInstantiation(C)->getName()
2466 ->getNameStart());
2467
Douglas Gregor572feb22010-03-18 18:04:21 +00002468 if (C.kind == CXCursor_MacroDefinition)
2469 return createCXString(getCursorMacroDefinition(C)->getName()
2470 ->getNameStart());
2471
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002472 if (clang_isDeclaration(C.kind))
2473 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002474
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002475 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002476}
2477
Ted Kremeneke68fff62010-02-17 00:41:32 +00002478CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002479 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002480 case CXCursor_FunctionDecl:
2481 return createCXString("FunctionDecl");
2482 case CXCursor_TypedefDecl:
2483 return createCXString("TypedefDecl");
2484 case CXCursor_EnumDecl:
2485 return createCXString("EnumDecl");
2486 case CXCursor_EnumConstantDecl:
2487 return createCXString("EnumConstantDecl");
2488 case CXCursor_StructDecl:
2489 return createCXString("StructDecl");
2490 case CXCursor_UnionDecl:
2491 return createCXString("UnionDecl");
2492 case CXCursor_ClassDecl:
2493 return createCXString("ClassDecl");
2494 case CXCursor_FieldDecl:
2495 return createCXString("FieldDecl");
2496 case CXCursor_VarDecl:
2497 return createCXString("VarDecl");
2498 case CXCursor_ParmDecl:
2499 return createCXString("ParmDecl");
2500 case CXCursor_ObjCInterfaceDecl:
2501 return createCXString("ObjCInterfaceDecl");
2502 case CXCursor_ObjCCategoryDecl:
2503 return createCXString("ObjCCategoryDecl");
2504 case CXCursor_ObjCProtocolDecl:
2505 return createCXString("ObjCProtocolDecl");
2506 case CXCursor_ObjCPropertyDecl:
2507 return createCXString("ObjCPropertyDecl");
2508 case CXCursor_ObjCIvarDecl:
2509 return createCXString("ObjCIvarDecl");
2510 case CXCursor_ObjCInstanceMethodDecl:
2511 return createCXString("ObjCInstanceMethodDecl");
2512 case CXCursor_ObjCClassMethodDecl:
2513 return createCXString("ObjCClassMethodDecl");
2514 case CXCursor_ObjCImplementationDecl:
2515 return createCXString("ObjCImplementationDecl");
2516 case CXCursor_ObjCCategoryImplDecl:
2517 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002518 case CXCursor_CXXMethod:
2519 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002520 case CXCursor_UnexposedDecl:
2521 return createCXString("UnexposedDecl");
2522 case CXCursor_ObjCSuperClassRef:
2523 return createCXString("ObjCSuperClassRef");
2524 case CXCursor_ObjCProtocolRef:
2525 return createCXString("ObjCProtocolRef");
2526 case CXCursor_ObjCClassRef:
2527 return createCXString("ObjCClassRef");
2528 case CXCursor_TypeRef:
2529 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002530 case CXCursor_TemplateRef:
2531 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002532 case CXCursor_NamespaceRef:
2533 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002534 case CXCursor_UnexposedExpr:
2535 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002536 case CXCursor_BlockExpr:
2537 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002538 case CXCursor_DeclRefExpr:
2539 return createCXString("DeclRefExpr");
2540 case CXCursor_MemberRefExpr:
2541 return createCXString("MemberRefExpr");
2542 case CXCursor_CallExpr:
2543 return createCXString("CallExpr");
2544 case CXCursor_ObjCMessageExpr:
2545 return createCXString("ObjCMessageExpr");
2546 case CXCursor_UnexposedStmt:
2547 return createCXString("UnexposedStmt");
2548 case CXCursor_InvalidFile:
2549 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002550 case CXCursor_InvalidCode:
2551 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002552 case CXCursor_NoDeclFound:
2553 return createCXString("NoDeclFound");
2554 case CXCursor_NotImplemented:
2555 return createCXString("NotImplemented");
2556 case CXCursor_TranslationUnit:
2557 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002558 case CXCursor_UnexposedAttr:
2559 return createCXString("UnexposedAttr");
2560 case CXCursor_IBActionAttr:
2561 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002562 case CXCursor_IBOutletAttr:
2563 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002564 case CXCursor_IBOutletCollectionAttr:
2565 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002566 case CXCursor_PreprocessingDirective:
2567 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002568 case CXCursor_MacroDefinition:
2569 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002570 case CXCursor_MacroInstantiation:
2571 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002572 case CXCursor_Namespace:
2573 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002574 case CXCursor_LinkageSpec:
2575 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002576 case CXCursor_CXXBaseSpecifier:
2577 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002578 case CXCursor_Constructor:
2579 return createCXString("CXXConstructor");
2580 case CXCursor_Destructor:
2581 return createCXString("CXXDestructor");
2582 case CXCursor_ConversionFunction:
2583 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002584 case CXCursor_TemplateTypeParameter:
2585 return createCXString("TemplateTypeParameter");
2586 case CXCursor_NonTypeTemplateParameter:
2587 return createCXString("NonTypeTemplateParameter");
2588 case CXCursor_TemplateTemplateParameter:
2589 return createCXString("TemplateTemplateParameter");
2590 case CXCursor_FunctionTemplate:
2591 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002592 case CXCursor_ClassTemplate:
2593 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002594 case CXCursor_ClassTemplatePartialSpecialization:
2595 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002596 case CXCursor_NamespaceAlias:
2597 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002598 case CXCursor_UsingDirective:
2599 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002600 case CXCursor_UsingDeclaration:
2601 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002602 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002603
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002604 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002605 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002606}
Steve Naroff89922f82009-08-31 00:59:03 +00002607
Ted Kremeneke68fff62010-02-17 00:41:32 +00002608enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2609 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002610 CXClientData client_data) {
2611 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2612 *BestCursor = cursor;
2613 return CXChildVisit_Recurse;
2614}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002615
Douglas Gregorb9790342010-01-22 21:44:22 +00002616CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2617 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002618 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002619
Douglas Gregorb9790342010-01-22 21:44:22 +00002620 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002621 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2622
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002623 // Translate the given source location to make it point at the beginning of
2624 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002625 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002626
2627 // Guard against an invalid SourceLocation, or we may assert in one
2628 // of the following calls.
2629 if (SLoc.isInvalid())
2630 return clang_getNullCursor();
2631
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002632 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2633 CXXUnit->getASTContext().getLangOptions());
2634
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002635 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2636 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002637 // FIXME: Would be great to have a "hint" cursor, then walk from that
2638 // hint cursor upward until we find a cursor whose source range encloses
2639 // the region of interest, rather than starting from the translation unit.
2640 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002641 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002642 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002643 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002644 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002645 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002646}
2647
Ted Kremenek73885552009-11-17 19:28:59 +00002648CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002649 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002650}
2651
2652unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002653 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002654}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002655
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002656unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002657 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2658}
2659
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002660unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002661 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2662}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002663
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002664unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002665 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2666}
2667
Douglas Gregor97b98722010-01-19 23:20:36 +00002668unsigned clang_isExpression(enum CXCursorKind K) {
2669 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2670}
2671
2672unsigned clang_isStatement(enum CXCursorKind K) {
2673 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2674}
2675
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002676unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2677 return K == CXCursor_TranslationUnit;
2678}
2679
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002680unsigned clang_isPreprocessing(enum CXCursorKind K) {
2681 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2682}
2683
Ted Kremenekad6eff62010-03-08 21:17:29 +00002684unsigned clang_isUnexposed(enum CXCursorKind K) {
2685 switch (K) {
2686 case CXCursor_UnexposedDecl:
2687 case CXCursor_UnexposedExpr:
2688 case CXCursor_UnexposedStmt:
2689 case CXCursor_UnexposedAttr:
2690 return true;
2691 default:
2692 return false;
2693 }
2694}
2695
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002696CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002697 return C.kind;
2698}
2699
Douglas Gregor98258af2010-01-18 22:46:11 +00002700CXSourceLocation clang_getCursorLocation(CXCursor C) {
2701 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002702 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002703 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002704 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2705 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002706 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002707 }
2708
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002709 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002710 std::pair<ObjCProtocolDecl *, SourceLocation> P
2711 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002712 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002713 }
2714
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002715 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002716 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2717 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002718 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002719 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002720
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002721 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002722 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002723 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002724 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002725
2726 case CXCursor_TemplateRef: {
2727 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2728 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2729 }
2730
Douglas Gregor69319002010-08-31 23:48:11 +00002731 case CXCursor_NamespaceRef: {
2732 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2733 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2734 }
2735
Ted Kremenek3064ef92010-08-27 21:34:58 +00002736 case CXCursor_CXXBaseSpecifier: {
2737 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2738 return clang_getNullLocation();
2739 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002740
Douglas Gregorf46034a2010-01-18 23:41:10 +00002741 default:
2742 // FIXME: Need a way to enumerate all non-reference cases.
2743 llvm_unreachable("Missed a reference kind");
2744 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002745 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002746
2747 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002748 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002749 getLocationFromExpr(getCursorExpr(C)));
2750
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002751 if (C.kind == CXCursor_PreprocessingDirective) {
2752 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2753 return cxloc::translateSourceLocation(getCursorContext(C), L);
2754 }
Douglas Gregor48072312010-03-18 15:23:44 +00002755
2756 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002757 SourceLocation L
2758 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002759 return cxloc::translateSourceLocation(getCursorContext(C), L);
2760 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002761
2762 if (C.kind == CXCursor_MacroDefinition) {
2763 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2764 return cxloc::translateSourceLocation(getCursorContext(C), L);
2765 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002766
Ted Kremenek9a700d22010-05-12 06:16:13 +00002767 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002768 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002769
Douglas Gregorf46034a2010-01-18 23:41:10 +00002770 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002771 SourceLocation Loc = D->getLocation();
2772 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2773 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002774 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002775}
Douglas Gregora7bde202010-01-19 00:34:46 +00002776
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002777} // end extern "C"
2778
2779static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002780 if (clang_isReference(C.kind)) {
2781 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002782 case CXCursor_ObjCSuperClassRef:
2783 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002784
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002785 case CXCursor_ObjCProtocolRef:
2786 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002787
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002788 case CXCursor_ObjCClassRef:
2789 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002790
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002791 case CXCursor_TypeRef:
2792 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002793
2794 case CXCursor_TemplateRef:
2795 return getCursorTemplateRef(C).second;
2796
Douglas Gregor69319002010-08-31 23:48:11 +00002797 case CXCursor_NamespaceRef:
2798 return getCursorNamespaceRef(C).second;
2799
Ted Kremenek3064ef92010-08-27 21:34:58 +00002800 case CXCursor_CXXBaseSpecifier:
2801 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2802 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002803
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002804 default:
2805 // FIXME: Need a way to enumerate all non-reference cases.
2806 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002807 }
2808 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002809
2810 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002811 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002812
2813 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002814 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002815
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002816 if (C.kind == CXCursor_PreprocessingDirective)
2817 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002818
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002819 if (C.kind == CXCursor_MacroInstantiation)
2820 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002821
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002822 if (C.kind == CXCursor_MacroDefinition)
2823 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002824
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002825 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2826 return getCursorDecl(C)->getSourceRange();
2827
2828 return SourceRange();
2829}
2830
2831extern "C" {
2832
2833CXSourceRange clang_getCursorExtent(CXCursor C) {
2834 SourceRange R = getRawCursorExtent(C);
2835 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002836 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002837
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002838 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002839}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002840
2841CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002842 if (clang_isInvalid(C.kind))
2843 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002844
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002845 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002846 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002847 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002848
Douglas Gregor97b98722010-01-19 23:20:36 +00002849 if (clang_isExpression(C.kind)) {
2850 Decl *D = getDeclFromExpr(getCursorExpr(C));
2851 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002852 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002853 return clang_getNullCursor();
2854 }
2855
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002856 if (C.kind == CXCursor_MacroInstantiation) {
2857 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2858 return MakeMacroDefinitionCursor(Def, CXXUnit);
2859 }
2860
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002861 if (!clang_isReference(C.kind))
2862 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002863
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002864 switch (C.kind) {
2865 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002866 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002867
2868 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002869 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002870
2871 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002872 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002873
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002874 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002875 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002876
2877 case CXCursor_TemplateRef:
2878 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2879
Douglas Gregor69319002010-08-31 23:48:11 +00002880 case CXCursor_NamespaceRef:
2881 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2882
Ted Kremenek3064ef92010-08-27 21:34:58 +00002883 case CXCursor_CXXBaseSpecifier: {
2884 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2885 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2886 CXXUnit));
2887 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002888
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002889 default:
2890 // We would prefer to enumerate all non-reference cursor kinds here.
2891 llvm_unreachable("Unhandled reference cursor kind");
2892 break;
2893 }
2894 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002895
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002896 return clang_getNullCursor();
2897}
2898
Douglas Gregorb6998662010-01-19 19:34:47 +00002899CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002900 if (clang_isInvalid(C.kind))
2901 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002902
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002903 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002904
Douglas Gregorb6998662010-01-19 19:34:47 +00002905 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002906 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002907 C = clang_getCursorReferenced(C);
2908 WasReference = true;
2909 }
2910
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002911 if (C.kind == CXCursor_MacroInstantiation)
2912 return clang_getCursorReferenced(C);
2913
Douglas Gregorb6998662010-01-19 19:34:47 +00002914 if (!clang_isDeclaration(C.kind))
2915 return clang_getNullCursor();
2916
2917 Decl *D = getCursorDecl(C);
2918 if (!D)
2919 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002920
Douglas Gregorb6998662010-01-19 19:34:47 +00002921 switch (D->getKind()) {
2922 // Declaration kinds that don't really separate the notions of
2923 // declaration and definition.
2924 case Decl::Namespace:
2925 case Decl::Typedef:
2926 case Decl::TemplateTypeParm:
2927 case Decl::EnumConstant:
2928 case Decl::Field:
2929 case Decl::ObjCIvar:
2930 case Decl::ObjCAtDefsField:
2931 case Decl::ImplicitParam:
2932 case Decl::ParmVar:
2933 case Decl::NonTypeTemplateParm:
2934 case Decl::TemplateTemplateParm:
2935 case Decl::ObjCCategoryImpl:
2936 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002937 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002938 case Decl::LinkageSpec:
2939 case Decl::ObjCPropertyImpl:
2940 case Decl::FileScopeAsm:
2941 case Decl::StaticAssert:
2942 case Decl::Block:
2943 return C;
2944
2945 // Declaration kinds that don't make any sense here, but are
2946 // nonetheless harmless.
2947 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002948 break;
2949
2950 // Declaration kinds for which the definition is not resolvable.
2951 case Decl::UnresolvedUsingTypename:
2952 case Decl::UnresolvedUsingValue:
2953 break;
2954
2955 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002956 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2957 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002958
2959 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002960 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002961
2962 case Decl::Enum:
2963 case Decl::Record:
2964 case Decl::CXXRecord:
2965 case Decl::ClassTemplateSpecialization:
2966 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002967 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002968 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002969 return clang_getNullCursor();
2970
2971 case Decl::Function:
2972 case Decl::CXXMethod:
2973 case Decl::CXXConstructor:
2974 case Decl::CXXDestructor:
2975 case Decl::CXXConversion: {
2976 const FunctionDecl *Def = 0;
2977 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002978 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002979 return clang_getNullCursor();
2980 }
2981
2982 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002983 // Ask the variable if it has a definition.
2984 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2985 return MakeCXCursor(Def, CXXUnit);
2986 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002987 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002988
Douglas Gregorb6998662010-01-19 19:34:47 +00002989 case Decl::FunctionTemplate: {
2990 const FunctionDecl *Def = 0;
2991 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002992 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002993 return clang_getNullCursor();
2994 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002995
Douglas Gregorb6998662010-01-19 19:34:47 +00002996 case Decl::ClassTemplate: {
2997 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002998 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002999 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003000 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003001 return clang_getNullCursor();
3002 }
3003
3004 case Decl::Using: {
3005 UsingDecl *Using = cast<UsingDecl>(D);
3006 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003007 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
3008 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00003009 S != SEnd; ++S) {
3010 if (Def != clang_getNullCursor()) {
3011 // FIXME: We have no way to return multiple results.
3012 return clang_getNullCursor();
3013 }
3014
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003015 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003016 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003017 }
3018
3019 return Def;
3020 }
3021
3022 case Decl::UsingShadow:
3023 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003024 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003025 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003026
3027 case Decl::ObjCMethod: {
3028 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3029 if (Method->isThisDeclarationADefinition())
3030 return C;
3031
3032 // Dig out the method definition in the associated
3033 // @implementation, if we have it.
3034 // FIXME: The ASTs should make finding the definition easier.
3035 if (ObjCInterfaceDecl *Class
3036 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3037 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3038 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3039 Method->isInstanceMethod()))
3040 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003041 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003042
3043 return clang_getNullCursor();
3044 }
3045
3046 case Decl::ObjCCategory:
3047 if (ObjCCategoryImplDecl *Impl
3048 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003049 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003050 return clang_getNullCursor();
3051
3052 case Decl::ObjCProtocol:
3053 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3054 return C;
3055 return clang_getNullCursor();
3056
3057 case Decl::ObjCInterface:
3058 // There are two notions of a "definition" for an Objective-C
3059 // class: the interface and its implementation. When we resolved a
3060 // reference to an Objective-C class, produce the @interface as
3061 // the definition; when we were provided with the interface,
3062 // produce the @implementation as the definition.
3063 if (WasReference) {
3064 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3065 return C;
3066 } else if (ObjCImplementationDecl *Impl
3067 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003068 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003069 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003070
Douglas Gregorb6998662010-01-19 19:34:47 +00003071 case Decl::ObjCProperty:
3072 // FIXME: We don't really know where to find the
3073 // ObjCPropertyImplDecls that implement this property.
3074 return clang_getNullCursor();
3075
3076 case Decl::ObjCCompatibleAlias:
3077 if (ObjCInterfaceDecl *Class
3078 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3079 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003080 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003081
Douglas Gregorb6998662010-01-19 19:34:47 +00003082 return clang_getNullCursor();
3083
3084 case Decl::ObjCForwardProtocol: {
3085 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
3086 if (Forward->protocol_size() == 1)
3087 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003088 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003089 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003090
3091 // FIXME: Cannot return multiple definitions.
3092 return clang_getNullCursor();
3093 }
3094
3095 case Decl::ObjCClass: {
3096 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
3097 if (Class->size() == 1) {
3098 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
3099 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003100 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003101 return clang_getNullCursor();
3102 }
3103
3104 // FIXME: Cannot return multiple definitions.
3105 return clang_getNullCursor();
3106 }
3107
3108 case Decl::Friend:
3109 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003110 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003111 return clang_getNullCursor();
3112
3113 case Decl::FriendTemplate:
3114 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003115 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003116 return clang_getNullCursor();
3117 }
3118
3119 return clang_getNullCursor();
3120}
3121
3122unsigned clang_isCursorDefinition(CXCursor C) {
3123 if (!clang_isDeclaration(C.kind))
3124 return 0;
3125
3126 return clang_getCursorDefinition(C) == C;
3127}
3128
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003129void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003130 const char **startBuf,
3131 const char **endBuf,
3132 unsigned *startLine,
3133 unsigned *startColumn,
3134 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003135 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003136 assert(getCursorDecl(C) && "CXCursor has null decl");
3137 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003138 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3139 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003140
Steve Naroff4ade6d62009-09-23 17:52:52 +00003141 SourceManager &SM = FD->getASTContext().getSourceManager();
3142 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3143 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3144 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3145 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3146 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3147 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3148}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003149
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003150void clang_enableStackTraces(void) {
3151 llvm::sys::PrintStackTraceOnErrorSignal();
3152}
3153
Ted Kremenekfb480492010-01-13 21:46:36 +00003154} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003155
Ted Kremenekfb480492010-01-13 21:46:36 +00003156//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003157// Token-based Operations.
3158//===----------------------------------------------------------------------===//
3159
3160/* CXToken layout:
3161 * int_data[0]: a CXTokenKind
3162 * int_data[1]: starting token location
3163 * int_data[2]: token length
3164 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003165 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003166 * otherwise unused.
3167 */
3168extern "C" {
3169
3170CXTokenKind clang_getTokenKind(CXToken CXTok) {
3171 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3172}
3173
3174CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3175 switch (clang_getTokenKind(CXTok)) {
3176 case CXToken_Identifier:
3177 case CXToken_Keyword:
3178 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003179 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3180 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003181
3182 case CXToken_Literal: {
3183 // We have stashed the starting pointer in the ptr_data field. Use it.
3184 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003185 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003186 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003187
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003188 case CXToken_Punctuation:
3189 case CXToken_Comment:
3190 break;
3191 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003192
3193 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003194 // deconstructing the source location.
3195 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3196 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003197 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003198
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003199 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3200 std::pair<FileID, unsigned> LocInfo
3201 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003202 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003203 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003204 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3205 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003206 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003207
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003208 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003209}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003210
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003211CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3212 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3213 if (!CXXUnit)
3214 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003215
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003216 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3217 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3218}
3219
3220CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3221 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003222 if (!CXXUnit)
3223 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003224
3225 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003226 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3227}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003228
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003229void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3230 CXToken **Tokens, unsigned *NumTokens) {
3231 if (Tokens)
3232 *Tokens = 0;
3233 if (NumTokens)
3234 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003235
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003236 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3237 if (!CXXUnit || !Tokens || !NumTokens)
3238 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003239
Douglas Gregorbdf60622010-03-05 21:16:25 +00003240 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3241
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003242 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003243 if (R.isInvalid())
3244 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003245
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003246 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3247 std::pair<FileID, unsigned> BeginLocInfo
3248 = SourceMgr.getDecomposedLoc(R.getBegin());
3249 std::pair<FileID, unsigned> EndLocInfo
3250 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003251
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003252 // Cannot tokenize across files.
3253 if (BeginLocInfo.first != EndLocInfo.first)
3254 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003255
3256 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003257 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003258 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003259 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003260 if (Invalid)
3261 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003262
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003263 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3264 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003265 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003266 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003267
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003268 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003269 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003270 llvm::SmallVector<CXToken, 32> CXTokens;
3271 Token Tok;
3272 do {
3273 // Lex the next token
3274 Lex.LexFromRawLexer(Tok);
3275 if (Tok.is(tok::eof))
3276 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003277
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003278 // Initialize the CXToken.
3279 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003280
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003281 // - Common fields
3282 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3283 CXTok.int_data[2] = Tok.getLength();
3284 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003285
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003286 // - Kind-specific fields
3287 if (Tok.isLiteral()) {
3288 CXTok.int_data[0] = CXToken_Literal;
3289 CXTok.ptr_data = (void *)Tok.getLiteralData();
3290 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003291 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003292 std::pair<FileID, unsigned> LocInfo
3293 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003294 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003295 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003296 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3297 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003298 return;
3299
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003300 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003301 IdentifierInfo *II
3302 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003303
3304 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3305 CXTok.int_data[0] = CXToken_Keyword;
3306 }
3307 else {
3308 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3309 CXToken_Identifier
3310 : CXToken_Keyword;
3311 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003312 CXTok.ptr_data = II;
3313 } else if (Tok.is(tok::comment)) {
3314 CXTok.int_data[0] = CXToken_Comment;
3315 CXTok.ptr_data = 0;
3316 } else {
3317 CXTok.int_data[0] = CXToken_Punctuation;
3318 CXTok.ptr_data = 0;
3319 }
3320 CXTokens.push_back(CXTok);
3321 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003322
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003323 if (CXTokens.empty())
3324 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003325
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003326 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3327 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3328 *NumTokens = CXTokens.size();
3329}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003330
Ted Kremenek6db61092010-05-05 00:55:15 +00003331void clang_disposeTokens(CXTranslationUnit TU,
3332 CXToken *Tokens, unsigned NumTokens) {
3333 free(Tokens);
3334}
3335
3336} // end: extern "C"
3337
3338//===----------------------------------------------------------------------===//
3339// Token annotation APIs.
3340//===----------------------------------------------------------------------===//
3341
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003342typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003343static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3344 CXCursor parent,
3345 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003346namespace {
3347class AnnotateTokensWorker {
3348 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003349 CXToken *Tokens;
3350 CXCursor *Cursors;
3351 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003352 unsigned TokIdx;
3353 CursorVisitor AnnotateVis;
3354 SourceManager &SrcMgr;
3355
3356 bool MoreTokens() const { return TokIdx < NumTokens; }
3357 unsigned NextToken() const { return TokIdx; }
3358 void AdvanceToken() { ++TokIdx; }
3359 SourceLocation GetTokenLoc(unsigned tokI) {
3360 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3361 }
3362
Ted Kremenek6db61092010-05-05 00:55:15 +00003363public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003364 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003365 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3366 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003367 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003368 NumTokens(numTokens), TokIdx(0),
3369 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3370 Decl::MaxPCHLevel, RegionOfInterest),
3371 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003372
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003373 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003374 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003375 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003376};
3377}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003378
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003379void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3380 // Walk the AST within the region of interest, annotating tokens
3381 // along the way.
3382 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003383
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003384 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3385 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3386 if (Pos != Annotated.end())
3387 Cursors[I] = Pos->second;
3388 }
3389
3390 // Finish up annotating any tokens left.
3391 if (!MoreTokens())
3392 return;
3393
3394 const CXCursor &C = clang_getNullCursor();
3395 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3396 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3397 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003398 }
3399}
3400
Ted Kremenek6db61092010-05-05 00:55:15 +00003401enum CXChildVisitResult
3402AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003403 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3404 // We can always annotate a preprocessing directive/macro instantiation.
3405 if (clang_isPreprocessing(cursor.kind)) {
3406 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003407 return CXChildVisit_Recurse;
3408 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003409
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003410 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003411
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003412 if (cursorRange.isInvalid())
3413 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003414
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003415 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3416
Ted Kremeneka333c662010-05-12 05:29:33 +00003417 // Adjust the annotated range based specific declarations.
3418 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3419 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003420 Decl *D = cxcursor::getCursorDecl(cursor);
3421 // Don't visit synthesized ObjC methods, since they have no syntatic
3422 // representation in the source.
3423 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3424 if (MD->isSynthesized())
3425 return CXChildVisit_Continue;
3426 }
3427 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003428 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3429 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003430 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003431 if (TLoc.isValid() &&
3432 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003433 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003434 }
3435 }
3436 }
3437
Ted Kremenek3f404602010-08-14 01:14:06 +00003438 // If the location of the cursor occurs within a macro instantiation, record
3439 // the spelling location of the cursor in our annotation map. We can then
3440 // paper over the token labelings during a post-processing step to try and
3441 // get cursor mappings for tokens that are the *arguments* of a macro
3442 // instantiation.
3443 if (L.isMacroID()) {
3444 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3445 // Only invalidate the old annotation if it isn't part of a preprocessing
3446 // directive. Here we assume that the default construction of CXCursor
3447 // results in CXCursor.kind being an initialized value (i.e., 0). If
3448 // this isn't the case, we can fix by doing lookup + insertion.
3449
3450 CXCursor &oldC = Annotated[rawEncoding];
3451 if (!clang_isPreprocessing(oldC.kind))
3452 oldC = cursor;
3453 }
3454
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003455 const enum CXCursorKind K = clang_getCursorKind(parent);
3456 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003457 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3458 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003459
3460 while (MoreTokens()) {
3461 const unsigned I = NextToken();
3462 SourceLocation TokLoc = GetTokenLoc(I);
3463 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3464 case RangeBefore:
3465 Cursors[I] = updateC;
3466 AdvanceToken();
3467 continue;
3468 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003469 case RangeOverlap:
3470 break;
3471 }
3472 break;
3473 }
3474
3475 // Visit children to get their cursor information.
3476 const unsigned BeforeChildren = NextToken();
3477 VisitChildren(cursor);
3478 const unsigned AfterChildren = NextToken();
3479
3480 // Adjust 'Last' to the last token within the extent of the cursor.
3481 while (MoreTokens()) {
3482 const unsigned I = NextToken();
3483 SourceLocation TokLoc = GetTokenLoc(I);
3484 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3485 case RangeBefore:
3486 assert(0 && "Infeasible");
3487 case RangeAfter:
3488 break;
3489 case RangeOverlap:
3490 Cursors[I] = updateC;
3491 AdvanceToken();
3492 continue;
3493 }
3494 break;
3495 }
3496 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003497
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003498 // Scan the tokens that are at the beginning of the cursor, but are not
3499 // capture by the child cursors.
3500
3501 // For AST elements within macros, rely on a post-annotate pass to
3502 // to correctly annotate the tokens with cursors. Otherwise we can
3503 // get confusing results of having tokens that map to cursors that really
3504 // are expanded by an instantiation.
3505 if (L.isMacroID())
3506 cursor = clang_getNullCursor();
3507
3508 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3509 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3510 break;
3511 Cursors[I] = cursor;
3512 }
3513 // Scan the tokens that are at the end of the cursor, but are not captured
3514 // but the child cursors.
3515 for (unsigned I = AfterChildren; I != Last; ++I)
3516 Cursors[I] = cursor;
3517
3518 TokIdx = Last;
3519 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003520}
3521
Ted Kremenek6db61092010-05-05 00:55:15 +00003522static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3523 CXCursor parent,
3524 CXClientData client_data) {
3525 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3526}
3527
3528extern "C" {
3529
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003530void clang_annotateTokens(CXTranslationUnit TU,
3531 CXToken *Tokens, unsigned NumTokens,
3532 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003533
3534 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003535 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003536
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003537 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003538 if (!CXXUnit) {
3539 // Any token we don't specifically annotate will have a NULL cursor.
3540 const CXCursor &C = clang_getNullCursor();
3541 for (unsigned I = 0; I != NumTokens; ++I)
3542 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003543 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003544 }
3545
Douglas Gregorbdf60622010-03-05 21:16:25 +00003546 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003547
Douglas Gregor0396f462010-03-19 05:22:59 +00003548 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003549 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003550 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3551 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003552 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3553 clang_getTokenLocation(TU,
3554 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003555
Douglas Gregor0396f462010-03-19 05:22:59 +00003556 // A mapping from the source locations found when re-lexing or traversing the
3557 // region of interest to the corresponding cursors.
3558 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003559
3560 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003561 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003562 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3563 std::pair<FileID, unsigned> BeginLocInfo
3564 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3565 std::pair<FileID, unsigned> EndLocInfo
3566 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003567
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003568 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003569 bool Invalid = false;
3570 if (BeginLocInfo.first == EndLocInfo.first &&
3571 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3572 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003573 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3574 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003575 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003576 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003577 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003578
3579 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003580 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003581 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003582 Token Tok;
3583 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003584
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003585 reprocess:
3586 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3587 // We have found a preprocessing directive. Gobble it up so that we
3588 // don't see it while preprocessing these tokens later, but keep track of
3589 // all of the token locations inside this preprocessing directive so that
3590 // we can annotate them appropriately.
3591 //
3592 // FIXME: Some simple tests here could identify macro definitions and
3593 // #undefs, to provide specific cursor kinds for those.
3594 std::vector<SourceLocation> Locations;
3595 do {
3596 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003597 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003598 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003599
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003600 using namespace cxcursor;
3601 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003602 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3603 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003604 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003605 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3606 Annotated[Locations[I].getRawEncoding()] = Cursor;
3607 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003608
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003609 if (Tok.isAtStartOfLine())
3610 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003611
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003612 continue;
3613 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003614
Douglas Gregor48072312010-03-18 15:23:44 +00003615 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003616 break;
3617 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003618 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003619
Douglas Gregor0396f462010-03-19 05:22:59 +00003620 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003621 // a specific cursor.
3622 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3623 CXXUnit, RegionOfInterest);
3624 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003625}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003626} // end: extern "C"
3627
3628//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003629// Operations for querying linkage of a cursor.
3630//===----------------------------------------------------------------------===//
3631
3632extern "C" {
3633CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003634 if (!clang_isDeclaration(cursor.kind))
3635 return CXLinkage_Invalid;
3636
Ted Kremenek16b42592010-03-03 06:36:57 +00003637 Decl *D = cxcursor::getCursorDecl(cursor);
3638 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3639 switch (ND->getLinkage()) {
3640 case NoLinkage: return CXLinkage_NoLinkage;
3641 case InternalLinkage: return CXLinkage_Internal;
3642 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3643 case ExternalLinkage: return CXLinkage_External;
3644 };
3645
3646 return CXLinkage_Invalid;
3647}
3648} // end: extern "C"
3649
3650//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003651// Operations for querying language of a cursor.
3652//===----------------------------------------------------------------------===//
3653
3654static CXLanguageKind getDeclLanguage(const Decl *D) {
3655 switch (D->getKind()) {
3656 default:
3657 break;
3658 case Decl::ImplicitParam:
3659 case Decl::ObjCAtDefsField:
3660 case Decl::ObjCCategory:
3661 case Decl::ObjCCategoryImpl:
3662 case Decl::ObjCClass:
3663 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003664 case Decl::ObjCForwardProtocol:
3665 case Decl::ObjCImplementation:
3666 case Decl::ObjCInterface:
3667 case Decl::ObjCIvar:
3668 case Decl::ObjCMethod:
3669 case Decl::ObjCProperty:
3670 case Decl::ObjCPropertyImpl:
3671 case Decl::ObjCProtocol:
3672 return CXLanguage_ObjC;
3673 case Decl::CXXConstructor:
3674 case Decl::CXXConversion:
3675 case Decl::CXXDestructor:
3676 case Decl::CXXMethod:
3677 case Decl::CXXRecord:
3678 case Decl::ClassTemplate:
3679 case Decl::ClassTemplatePartialSpecialization:
3680 case Decl::ClassTemplateSpecialization:
3681 case Decl::Friend:
3682 case Decl::FriendTemplate:
3683 case Decl::FunctionTemplate:
3684 case Decl::LinkageSpec:
3685 case Decl::Namespace:
3686 case Decl::NamespaceAlias:
3687 case Decl::NonTypeTemplateParm:
3688 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003689 case Decl::TemplateTemplateParm:
3690 case Decl::TemplateTypeParm:
3691 case Decl::UnresolvedUsingTypename:
3692 case Decl::UnresolvedUsingValue:
3693 case Decl::Using:
3694 case Decl::UsingDirective:
3695 case Decl::UsingShadow:
3696 return CXLanguage_CPlusPlus;
3697 }
3698
3699 return CXLanguage_C;
3700}
3701
3702extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003703
3704enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3705 if (clang_isDeclaration(cursor.kind))
3706 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3707 if (D->hasAttr<UnavailableAttr>() ||
3708 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3709 return CXAvailability_Available;
3710
3711 if (D->hasAttr<DeprecatedAttr>())
3712 return CXAvailability_Deprecated;
3713 }
3714
3715 return CXAvailability_Available;
3716}
3717
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003718CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3719 if (clang_isDeclaration(cursor.kind))
3720 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3721
3722 return CXLanguage_Invalid;
3723}
3724} // end: extern "C"
3725
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003726
3727//===----------------------------------------------------------------------===//
3728// C++ AST instrospection.
3729//===----------------------------------------------------------------------===//
3730
3731extern "C" {
3732unsigned clang_CXXMethod_isStatic(CXCursor C) {
3733 if (!clang_isDeclaration(C.kind))
3734 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003735
3736 CXXMethodDecl *Method = 0;
3737 Decl *D = cxcursor::getCursorDecl(C);
3738 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3739 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3740 else
3741 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3742 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003743}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003744
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003745} // end: extern "C"
3746
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003747//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003748// Attribute introspection.
3749//===----------------------------------------------------------------------===//
3750
3751extern "C" {
3752CXType clang_getIBOutletCollectionType(CXCursor C) {
3753 if (C.kind != CXCursor_IBOutletCollectionAttr)
3754 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3755
3756 IBOutletCollectionAttr *A =
3757 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3758
3759 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3760}
3761} // end: extern "C"
3762
3763//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003764// CXString Operations.
3765//===----------------------------------------------------------------------===//
3766
3767extern "C" {
3768const char *clang_getCString(CXString string) {
3769 return string.Spelling;
3770}
3771
3772void clang_disposeString(CXString string) {
3773 if (string.MustFreeString && string.Spelling)
3774 free((void*)string.Spelling);
3775}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003776
Ted Kremenekfb480492010-01-13 21:46:36 +00003777} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003778
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003779namespace clang { namespace cxstring {
3780CXString createCXString(const char *String, bool DupString){
3781 CXString Str;
3782 if (DupString) {
3783 Str.Spelling = strdup(String);
3784 Str.MustFreeString = 1;
3785 } else {
3786 Str.Spelling = String;
3787 Str.MustFreeString = 0;
3788 }
3789 return Str;
3790}
3791
3792CXString createCXString(llvm::StringRef String, bool DupString) {
3793 CXString Result;
3794 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3795 char *Spelling = (char *)malloc(String.size() + 1);
3796 memmove(Spelling, String.data(), String.size());
3797 Spelling[String.size()] = 0;
3798 Result.Spelling = Spelling;
3799 Result.MustFreeString = 1;
3800 } else {
3801 Result.Spelling = String.data();
3802 Result.MustFreeString = 0;
3803 }
3804 return Result;
3805}
3806}}
3807
Ted Kremenek04bb7162010-01-22 22:44:15 +00003808//===----------------------------------------------------------------------===//
3809// Misc. utility functions.
3810//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003811
Ted Kremenek04bb7162010-01-22 22:44:15 +00003812extern "C" {
3813
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003814CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003815 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003816}
3817
3818} // end: extern "C"