blob: 5a3084c49ba766a54780d453153a40bec4f5c158 [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);
Ted Kremenek79758f62010-02-18 22:36:18 +0000315 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
316 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
317 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000318 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000319 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000320 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000321 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000322 bool VisitUsingDecl(UsingDecl *D);
323 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
324 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000325
Douglas Gregor01829d32010-08-31 14:41:23 +0000326 // Name visitor
327 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000328 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000329
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000330 // Template visitors
331 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000332 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000333 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
334
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000335 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000336 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000337 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000338 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000339 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
340 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000341 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000342 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000343 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000344 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
345 bool VisitPointerTypeLoc(PointerTypeLoc TL);
346 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
347 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
348 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
349 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000350 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000351 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000352 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000353 // FIXME: Implement visitors here when the unimplemented TypeLocs get
354 // implemented
355 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
356 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000357
Douglas Gregora59e3902010-01-21 23:27:09 +0000358 // Statement visitors
359 bool VisitStmt(Stmt *S);
360 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000361 // FIXME: LabelStmt label?
362 bool VisitIfStmt(IfStmt *S);
363 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000364 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000365 bool VisitWhileStmt(WhileStmt *S);
366 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000367
Douglas Gregor336fd812010-01-23 00:40:08 +0000368 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000369 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000370 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000371 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000372 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000373 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000374 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000375 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000376 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000377 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfbb4c982010-09-02 21:07:44 +0000378 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000379 // FIXME: AddrLabelExpr (once we have cursors for labels)
380 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
381 bool VisitVAArgExpr(VAArgExpr *E);
382 // FIXME: InitListExpr (for the designators)
383 // FIXME: DesignatedInitExpr
Douglas Gregor94802292010-09-02 21:20:16 +0000384 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000385 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000386 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000387 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
388 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000389 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000390 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000391 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000392 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000393 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000394 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000395 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000396 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000397};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000398
Ted Kremenekab188932010-01-05 19:32:54 +0000399} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000400
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000401static SourceRange getRawCursorExtent(CXCursor C);
402
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000403RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000404 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
405}
406
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407/// \brief Visit the given cursor and, if requested by the visitor,
408/// its children.
409///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000410/// \param Cursor the cursor to visit.
411///
412/// \param CheckRegionOfInterest if true, then the caller already checked that
413/// this cursor is within the region of interest.
414///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000415/// \returns true if the visitation should be aborted, false if it
416/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000417bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418 if (clang_isInvalid(Cursor.kind))
419 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000420
Douglas Gregorb1373d02010-01-20 20:59:29 +0000421 if (clang_isDeclaration(Cursor.kind)) {
422 Decl *D = getCursorDecl(Cursor);
423 assert(D && "Invalid declaration cursor");
424 if (D->getPCHLevel() > MaxPCHLevel)
425 return false;
426
427 if (D->isImplicit())
428 return false;
429 }
430
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000431 // If we have a range of interest, and this cursor doesn't intersect with it,
432 // we're done.
433 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000434 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000435 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000436 return false;
437 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000438
Douglas Gregorb1373d02010-01-20 20:59:29 +0000439 switch (Visitor(Cursor, Parent, ClientData)) {
440 case CXChildVisit_Break:
441 return true;
442
443 case CXChildVisit_Continue:
444 return false;
445
446 case CXChildVisit_Recurse:
447 return VisitChildren(Cursor);
448 }
449
Douglas Gregorfd643772010-01-25 16:45:46 +0000450 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451}
452
Douglas Gregor788f5a12010-03-20 00:41:21 +0000453std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
454CursorVisitor::getPreprocessedEntities() {
455 PreprocessingRecord &PPRec
456 = *TU->getPreprocessor().getPreprocessingRecord();
457
458 bool OnlyLocalDecls
459 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
460
461 // There is no region of interest; we have to walk everything.
462 if (RegionOfInterest.isInvalid())
463 return std::make_pair(PPRec.begin(OnlyLocalDecls),
464 PPRec.end(OnlyLocalDecls));
465
466 // Find the file in which the region of interest lands.
467 SourceManager &SM = TU->getSourceManager();
468 std::pair<FileID, unsigned> Begin
469 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
470 std::pair<FileID, unsigned> End
471 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
472
473 // The region of interest spans files; we have to walk everything.
474 if (Begin.first != End.first)
475 return std::make_pair(PPRec.begin(OnlyLocalDecls),
476 PPRec.end(OnlyLocalDecls));
477
478 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
479 = TU->getPreprocessedEntitiesByFile();
480 if (ByFileMap.empty()) {
481 // Build the mapping from files to sets of preprocessed entities.
482 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
483 EEnd = PPRec.end(OnlyLocalDecls);
484 E != EEnd; ++E) {
485 std::pair<FileID, unsigned> P
486 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
487 ByFileMap[P.first].push_back(*E);
488 }
489 }
490
491 return std::make_pair(ByFileMap[Begin.first].begin(),
492 ByFileMap[Begin.first].end());
493}
494
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495/// \brief Visit the children of the given cursor.
496///
497/// \returns true if the visitation should be aborted, false if it
498/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000499bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000500 if (clang_isReference(Cursor.kind)) {
501 // By definition, references have no children.
502 return false;
503 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000504
505 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000506 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000507 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000508
Douglas Gregorb1373d02010-01-20 20:59:29 +0000509 if (clang_isDeclaration(Cursor.kind)) {
510 Decl *D = getCursorDecl(Cursor);
511 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000512 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000514
Douglas Gregora59e3902010-01-21 23:27:09 +0000515 if (clang_isStatement(Cursor.kind))
516 return Visit(getCursorStmt(Cursor));
517 if (clang_isExpression(Cursor.kind))
518 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000519
Douglas Gregorb1373d02010-01-20 20:59:29 +0000520 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000521 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000522 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
523 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000524 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
525 TLEnd = CXXUnit->top_level_end();
526 TL != TLEnd; ++TL) {
527 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000528 return true;
529 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000530 } else if (VisitDeclContext(
531 CXXUnit->getASTContext().getTranslationUnitDecl()))
532 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000533
Douglas Gregor0396f462010-03-19 05:22:59 +0000534 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000535 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000536 // FIXME: Once we have the ability to deserialize a preprocessing record,
537 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000538 PreprocessingRecord::iterator E, EEnd;
539 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000540 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
541 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
542 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000543
Douglas Gregor0396f462010-03-19 05:22:59 +0000544 continue;
545 }
546
547 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
548 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
549 return true;
550
551 continue;
552 }
553 }
554 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000555 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000556 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000557
Douglas Gregorb1373d02010-01-20 20:59:29 +0000558 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 return false;
560}
561
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000562bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000563 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
564 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000565
Ted Kremenek664cffd2010-07-22 11:30:19 +0000566 if (Stmt *Body = B->getBody())
567 return Visit(MakeCXCursor(Body, StmtParent, TU));
568
569 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000570}
571
Douglas Gregorb1373d02010-01-20 20:59:29 +0000572bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000573 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000574 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000575
Ted Kremenek23173d72010-05-18 21:09:07 +0000576 Decl *D = *I;
577 if (D->getLexicalDeclContext() != DC)
578 continue;
579
580 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000581
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000582 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000583 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000584 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000585 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000586
587 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000588 case RangeBefore:
589 // This declaration comes before the region of interest; skip it.
590 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000591
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000592 case RangeAfter:
593 // This declaration comes after the region of interest; we're done.
594 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000595
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000596 case RangeOverlap:
597 // This declaration overlaps the region of interest; visit it.
598 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000599 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000600 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000601
Daniel Dunbard52864b2010-02-14 10:02:57 +0000602 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000603 return true;
604 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000605
Douglas Gregorb1373d02010-01-20 20:59:29 +0000606 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000607}
608
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000609bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
610 llvm_unreachable("Translation units are visited directly by Visit()");
611 return false;
612}
613
614bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
615 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
616 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000617
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000618 return false;
619}
620
621bool CursorVisitor::VisitTagDecl(TagDecl *D) {
622 return VisitDeclContext(D);
623}
624
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000625bool CursorVisitor::VisitClassTemplateSpecializationDecl(
626 ClassTemplateSpecializationDecl *D) {
627 bool ShouldVisitBody = false;
628 switch (D->getSpecializationKind()) {
629 case TSK_Undeclared:
630 case TSK_ImplicitInstantiation:
631 // Nothing to visit
632 return false;
633
634 case TSK_ExplicitInstantiationDeclaration:
635 case TSK_ExplicitInstantiationDefinition:
636 break;
637
638 case TSK_ExplicitSpecialization:
639 ShouldVisitBody = true;
640 break;
641 }
642
643 // Visit the template arguments used in the specialization.
644 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
645 TypeLoc TL = SpecType->getTypeLoc();
646 if (TemplateSpecializationTypeLoc *TSTLoc
647 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
648 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
649 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
650 return true;
651 }
652 }
653
654 if (ShouldVisitBody && VisitCXXRecordDecl(D))
655 return true;
656
657 return false;
658}
659
Douglas Gregor74dbe642010-08-31 19:31:58 +0000660bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
661 ClassTemplatePartialSpecializationDecl *D) {
662 // FIXME: Visit the "outer" template parameter lists on the TagDecl
663 // before visiting these template parameters.
664 if (VisitTemplateParameters(D->getTemplateParameters()))
665 return true;
666
667 // Visit the partial specialization arguments.
668 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
669 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
670 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
671 return true;
672
673 return VisitCXXRecordDecl(D);
674}
675
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000676bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000677 // Visit the default argument.
678 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
679 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
680 if (Visit(DefArg->getTypeLoc()))
681 return true;
682
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000683 return false;
684}
685
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000686bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
687 if (Expr *Init = D->getInitExpr())
688 return Visit(MakeCXCursor(Init, StmtParent, TU));
689 return false;
690}
691
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000692bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
693 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
694 if (Visit(TSInfo->getTypeLoc()))
695 return true;
696
697 return false;
698}
699
Douglas Gregorb1373d02010-01-20 20:59:29 +0000700bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000701 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
702 // Visit the function declaration's syntactic components in the order
703 // written. This requires a bit of work.
704 TypeLoc TL = TSInfo->getTypeLoc();
705 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
706
707 // If we have a function declared directly (without the use of a typedef),
708 // visit just the return type. Otherwise, just visit the function's type
709 // now.
710 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
711 (!FTL && Visit(TL)))
712 return true;
713
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000714 // Visit the nested-name-specifier, if present.
715 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
716 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
717 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000718
719 // Visit the declaration name.
720 if (VisitDeclarationNameInfo(ND->getNameInfo()))
721 return true;
722
723 // FIXME: Visit explicitly-specified template arguments!
724
725 // Visit the function parameters, if we have a function type.
726 if (FTL && VisitFunctionTypeLoc(*FTL, true))
727 return true;
728
729 // FIXME: Attributes?
730 }
731
Douglas Gregora59e3902010-01-21 23:27:09 +0000732 if (ND->isThisDeclarationADefinition() &&
733 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
734 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000735
Douglas Gregorb1373d02010-01-20 20:59:29 +0000736 return false;
737}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000738
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000739bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
740 if (VisitDeclaratorDecl(D))
741 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000742
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000743 if (Expr *BitWidth = D->getBitWidth())
744 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000745
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000746 return false;
747}
748
749bool CursorVisitor::VisitVarDecl(VarDecl *D) {
750 if (VisitDeclaratorDecl(D))
751 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000752
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000753 if (Expr *Init = D->getInit())
754 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000755
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000756 return false;
757}
758
Douglas Gregor84b51d72010-09-01 20:16:53 +0000759bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
760 if (VisitDeclaratorDecl(D))
761 return true;
762
763 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
764 if (Expr *DefArg = D->getDefaultArgument())
765 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
766
767 return false;
768}
769
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000770bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
771 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
772 // before visiting these template parameters.
773 if (VisitTemplateParameters(D->getTemplateParameters()))
774 return true;
775
776 return VisitFunctionDecl(D->getTemplatedDecl());
777}
778
Douglas Gregor39d6f072010-08-31 19:02:00 +0000779bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
780 // FIXME: Visit the "outer" template parameter lists on the TagDecl
781 // before visiting these template parameters.
782 if (VisitTemplateParameters(D->getTemplateParameters()))
783 return true;
784
785 return VisitCXXRecordDecl(D->getTemplatedDecl());
786}
787
Douglas Gregor84b51d72010-09-01 20:16:53 +0000788bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
789 if (VisitTemplateParameters(D->getTemplateParameters()))
790 return true;
791
792 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
793 VisitTemplateArgumentLoc(D->getDefaultArgument()))
794 return true;
795
796 return false;
797}
798
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000799bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000800 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
801 if (Visit(TSInfo->getTypeLoc()))
802 return true;
803
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 PEnd = ND->param_end();
806 P != PEnd; ++P) {
807 if (Visit(MakeCXCursor(*P, TU)))
808 return true;
809 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000810
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000811 if (ND->isThisDeclarationADefinition() &&
812 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
813 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000814
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000815 return false;
816}
817
Douglas Gregora59e3902010-01-21 23:27:09 +0000818bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
819 return VisitDeclContext(D);
820}
821
Douglas Gregorb1373d02010-01-20 20:59:29 +0000822bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000823 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
824 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000825 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000826
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000827 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
828 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
829 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000830 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000831 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000832
Douglas Gregora59e3902010-01-21 23:27:09 +0000833 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000834}
835
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000836bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
837 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
838 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
839 E = PID->protocol_end(); I != E; ++I, ++PL)
840 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
841 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000843 return VisitObjCContainerDecl(PID);
844}
845
Ted Kremenek23173d72010-05-18 21:09:07 +0000846bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000847 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000848 return true;
849
Ted Kremenek23173d72010-05-18 21:09:07 +0000850 // FIXME: This implements a workaround with @property declarations also being
851 // installed in the DeclContext for the @interface. Eventually this code
852 // should be removed.
853 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
854 if (!CDecl || !CDecl->IsClassExtension())
855 return false;
856
857 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
858 if (!ID)
859 return false;
860
861 IdentifierInfo *PropertyId = PD->getIdentifier();
862 ObjCPropertyDecl *prevDecl =
863 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
864
865 if (!prevDecl)
866 return false;
867
868 // Visit synthesized methods since they will be skipped when visiting
869 // the @interface.
870 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
871 if (MD->isSynthesized())
872 if (Visit(MakeCXCursor(MD, TU)))
873 return true;
874
875 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
876 if (MD->isSynthesized())
877 if (Visit(MakeCXCursor(MD, TU)))
878 return true;
879
880 return false;
881}
882
Douglas Gregorb1373d02010-01-20 20:59:29 +0000883bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000884 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000885 if (D->getSuperClass() &&
886 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000887 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000888 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000889 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000890
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000891 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
892 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
893 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000894 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000895 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000896
Douglas Gregora59e3902010-01-21 23:27:09 +0000897 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000898}
899
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000900bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
901 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000902}
903
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000904bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000905 // 'ID' could be null when dealing with invalid code.
906 if (ObjCInterfaceDecl *ID = D->getClassInterface())
907 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
908 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000909
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000910 return VisitObjCImplDecl(D);
911}
912
913bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
914#if 0
915 // Issue callbacks for super class.
916 // FIXME: No source location information!
917 if (D->getSuperClass() &&
918 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000919 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000920 TU)))
921 return true;
922#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000923
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000924 return VisitObjCImplDecl(D);
925}
926
927bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
928 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
929 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
930 E = D->protocol_end();
931 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000932 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000933 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000934
935 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000936}
937
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000938bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
939 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
940 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
941 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000942
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000943 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000944}
945
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000946bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
947 return VisitDeclContext(D);
948}
949
Douglas Gregor69319002010-08-31 23:48:11 +0000950bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000951 // Visit nested-name-specifier.
952 if (NestedNameSpecifier *Qualifier = D->getQualifier())
953 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
954 return true;
Douglas Gregor69319002010-08-31 23:48:11 +0000955
956 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
957 D->getTargetNameLoc(), TU));
958}
959
Douglas Gregor7e242562010-09-01 19:52:22 +0000960bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000961 // Visit nested-name-specifier.
962 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
963 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
964 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +0000965
966 // FIXME: Provide a multi-reference of some kind for all of the declarations
967 // that the using declaration refers to. We don't have this kind of cursor
968 // yet.
969
970 return VisitDeclarationNameInfo(D->getNameInfo());
971}
972
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000973bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000974 // Visit nested-name-specifier.
975 if (NestedNameSpecifier *Qualifier = D->getQualifier())
976 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
977 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000978
979 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
980 D->getIdentLocation(), TU));
981}
982
Douglas Gregor7e242562010-09-01 19:52:22 +0000983bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000984 // Visit nested-name-specifier.
985 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
986 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
987 return true;
988
Douglas Gregor7e242562010-09-01 19:52:22 +0000989 return VisitDeclarationNameInfo(D->getNameInfo());
990}
991
992bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
993 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000994 // Visit nested-name-specifier.
995 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
996 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
997 return true;
998
Douglas Gregor7e242562010-09-01 19:52:22 +0000999 return false;
1000}
1001
Douglas Gregor01829d32010-08-31 14:41:23 +00001002bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1003 switch (Name.getName().getNameKind()) {
1004 case clang::DeclarationName::Identifier:
1005 case clang::DeclarationName::CXXLiteralOperatorName:
1006 case clang::DeclarationName::CXXOperatorName:
1007 case clang::DeclarationName::CXXUsingDirective:
1008 return false;
1009
1010 case clang::DeclarationName::CXXConstructorName:
1011 case clang::DeclarationName::CXXDestructorName:
1012 case clang::DeclarationName::CXXConversionFunctionName:
1013 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1014 return Visit(TSInfo->getTypeLoc());
1015 return false;
1016
1017 case clang::DeclarationName::ObjCZeroArgSelector:
1018 case clang::DeclarationName::ObjCOneArgSelector:
1019 case clang::DeclarationName::ObjCMultiArgSelector:
1020 // FIXME: Per-identifier location info?
1021 return false;
1022 }
1023
1024 return false;
1025}
1026
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001027bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1028 SourceRange Range) {
1029 // FIXME: This whole routine is a hack to work around the lack of proper
1030 // source information in nested-name-specifiers (PR5791). Since we do have
1031 // a beginning source location, we can visit the first component of the
1032 // nested-name-specifier, if it's a single-token component.
1033 if (!NNS)
1034 return false;
1035
1036 // Get the first component in the nested-name-specifier.
1037 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1038 NNS = Prefix;
1039
1040 switch (NNS->getKind()) {
1041 case NestedNameSpecifier::Namespace:
1042 // FIXME: The token at this source location might actually have been a
1043 // namespace alias, but we don't model that. Lame!
1044 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1045 TU));
1046
1047 case NestedNameSpecifier::TypeSpec: {
1048 // If the type has a form where we know that the beginning of the source
1049 // range matches up with a reference cursor. Visit the appropriate reference
1050 // cursor.
1051 Type *T = NNS->getAsType();
1052 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1053 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1054 if (const TagType *Tag = dyn_cast<TagType>(T))
1055 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1056 if (const TemplateSpecializationType *TST
1057 = dyn_cast<TemplateSpecializationType>(T))
1058 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1059 break;
1060 }
1061
1062 case NestedNameSpecifier::TypeSpecWithTemplate:
1063 case NestedNameSpecifier::Global:
1064 case NestedNameSpecifier::Identifier:
1065 break;
1066 }
1067
1068 return false;
1069}
1070
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001071bool CursorVisitor::VisitTemplateParameters(
1072 const TemplateParameterList *Params) {
1073 if (!Params)
1074 return false;
1075
1076 for (TemplateParameterList::const_iterator P = Params->begin(),
1077 PEnd = Params->end();
1078 P != PEnd; ++P) {
1079 if (Visit(MakeCXCursor(*P, TU)))
1080 return true;
1081 }
1082
1083 return false;
1084}
1085
Douglas Gregor0b36e612010-08-31 20:37:03 +00001086bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1087 switch (Name.getKind()) {
1088 case TemplateName::Template:
1089 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1090
1091 case TemplateName::OverloadedTemplate:
1092 // FIXME: We need a way to return multiple lookup results in a single
1093 // cursor.
1094 return false;
1095
1096 case TemplateName::DependentTemplate:
1097 // FIXME: Visit nested-name-specifier.
1098 return false;
1099
1100 case TemplateName::QualifiedTemplate:
1101 // FIXME: Visit nested-name-specifier.
1102 return Visit(MakeCursorTemplateRef(
1103 Name.getAsQualifiedTemplateName()->getDecl(),
1104 Loc, TU));
1105 }
1106
1107 return false;
1108}
1109
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001110bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1111 switch (TAL.getArgument().getKind()) {
1112 case TemplateArgument::Null:
1113 case TemplateArgument::Integral:
1114 return false;
1115
1116 case TemplateArgument::Pack:
1117 // FIXME: Implement when variadic templates come along.
1118 return false;
1119
1120 case TemplateArgument::Type:
1121 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1122 return Visit(TSInfo->getTypeLoc());
1123 return false;
1124
1125 case TemplateArgument::Declaration:
1126 if (Expr *E = TAL.getSourceDeclExpression())
1127 return Visit(MakeCXCursor(E, StmtParent, TU));
1128 return false;
1129
1130 case TemplateArgument::Expression:
1131 if (Expr *E = TAL.getSourceExpression())
1132 return Visit(MakeCXCursor(E, StmtParent, TU));
1133 return false;
1134
1135 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001136 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1137 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001138 }
1139
1140 return false;
1141}
1142
Ted Kremeneka0536d82010-05-07 01:04:29 +00001143bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1144 return VisitDeclContext(D);
1145}
1146
Douglas Gregor01829d32010-08-31 14:41:23 +00001147bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1148 return Visit(TL.getUnqualifiedLoc());
1149}
1150
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001151bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1152 ASTContext &Context = TU->getASTContext();
1153
1154 // Some builtin types (such as Objective-C's "id", "sel", and
1155 // "Class") have associated declarations. Create cursors for those.
1156 QualType VisitType;
1157 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001158 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001159 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001160 case BuiltinType::Char_U:
1161 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001162 case BuiltinType::Char16:
1163 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001164 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001165 case BuiltinType::UInt:
1166 case BuiltinType::ULong:
1167 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001168 case BuiltinType::UInt128:
1169 case BuiltinType::Char_S:
1170 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001171 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001172 case BuiltinType::Short:
1173 case BuiltinType::Int:
1174 case BuiltinType::Long:
1175 case BuiltinType::LongLong:
1176 case BuiltinType::Int128:
1177 case BuiltinType::Float:
1178 case BuiltinType::Double:
1179 case BuiltinType::LongDouble:
1180 case BuiltinType::NullPtr:
1181 case BuiltinType::Overload:
1182 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001183 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001184
1185 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001186 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001187
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001188 case BuiltinType::ObjCId:
1189 VisitType = Context.getObjCIdType();
1190 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001191
1192 case BuiltinType::ObjCClass:
1193 VisitType = Context.getObjCClassType();
1194 break;
1195
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001196 case BuiltinType::ObjCSel:
1197 VisitType = Context.getObjCSelType();
1198 break;
1199 }
1200
1201 if (!VisitType.isNull()) {
1202 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001203 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001204 TU));
1205 }
1206
1207 return false;
1208}
1209
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001210bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1211 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1212}
1213
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001214bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1215 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1216}
1217
1218bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1219 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1220}
1221
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001222bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1223 // FIXME: We can't visit the template template parameter, but there's
1224 // no context information with which we can match up the depth/index in the
1225 // type to the appropriate
1226 return false;
1227}
1228
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001229bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1230 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1231 return true;
1232
John McCallc12c5bb2010-05-15 11:32:37 +00001233 return false;
1234}
1235
1236bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1237 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1238 return true;
1239
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001240 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1241 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1242 TU)))
1243 return true;
1244 }
1245
1246 return false;
1247}
1248
1249bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001250 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001251}
1252
1253bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1254 return Visit(TL.getPointeeLoc());
1255}
1256
1257bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1258 return Visit(TL.getPointeeLoc());
1259}
1260
1261bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1262 return Visit(TL.getPointeeLoc());
1263}
1264
1265bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001266 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001267}
1268
1269bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001270 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001271}
1272
Douglas Gregor01829d32010-08-31 14:41:23 +00001273bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1274 bool SkipResultType) {
1275 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001276 return true;
1277
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001278 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001279 if (Decl *D = TL.getArg(I))
1280 if (Visit(MakeCXCursor(D, TU)))
1281 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001282
1283 return false;
1284}
1285
1286bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1287 if (Visit(TL.getElementLoc()))
1288 return true;
1289
1290 if (Expr *Size = TL.getSizeExpr())
1291 return Visit(MakeCXCursor(Size, StmtParent, TU));
1292
1293 return false;
1294}
1295
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001296bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1297 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001298 // Visit the template name.
1299 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1300 TL.getTemplateNameLoc()))
1301 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001302
1303 // Visit the template arguments.
1304 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1305 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1306 return true;
1307
1308 return false;
1309}
1310
Douglas Gregor2332c112010-01-21 20:48:56 +00001311bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1312 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1313}
1314
1315bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1316 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1317 return Visit(TSInfo->getTypeLoc());
1318
1319 return false;
1320}
1321
Douglas Gregora59e3902010-01-21 23:27:09 +00001322bool CursorVisitor::VisitStmt(Stmt *S) {
1323 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1324 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001325 if (Stmt *C = *Child)
1326 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1327 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001328 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001329
Douglas Gregora59e3902010-01-21 23:27:09 +00001330 return false;
1331}
1332
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001333bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1334 // Specially handle CaseStmts because they can be nested, e.g.:
1335 //
1336 // case 1:
1337 // case 2:
1338 //
1339 // In this case the second CaseStmt is the child of the first. Walking
1340 // these recursively can blow out the stack.
1341 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1342 while (true) {
1343 // Set the Parent field to Cursor, then back to its old value once we're
1344 // done.
1345 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1346
1347 if (Stmt *LHS = S->getLHS())
1348 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1349 return true;
1350 if (Stmt *RHS = S->getRHS())
1351 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1352 return true;
1353 if (Stmt *SubStmt = S->getSubStmt()) {
1354 if (!isa<CaseStmt>(SubStmt))
1355 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1356
1357 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1358 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1359 Cursor = MakeCXCursor(CS, StmtParent, TU);
1360 if (RegionOfInterest.isValid()) {
1361 SourceRange Range = CS->getSourceRange();
1362 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1363 return false;
1364 }
1365
1366 switch (Visitor(Cursor, Parent, ClientData)) {
1367 case CXChildVisit_Break: return true;
1368 case CXChildVisit_Continue: return false;
1369 case CXChildVisit_Recurse:
1370 // Perform tail-recursion manually.
1371 S = CS;
1372 continue;
1373 }
1374 }
1375 return false;
1376 }
1377}
1378
Douglas Gregora59e3902010-01-21 23:27:09 +00001379bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1380 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1381 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001382 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001383 return true;
1384 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001385
Douglas Gregora59e3902010-01-21 23:27:09 +00001386 return false;
1387}
1388
Douglas Gregorf5bab412010-01-22 01:00:11 +00001389bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1390 if (VarDecl *Var = S->getConditionVariable()) {
1391 if (Visit(MakeCXCursor(Var, TU)))
1392 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001393 }
1394
Douglas Gregor263b47b2010-01-25 16:12:32 +00001395 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1396 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001397 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1398 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001399 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1400 return true;
1401
1402 return false;
1403}
1404
1405bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1406 if (VarDecl *Var = S->getConditionVariable()) {
1407 if (Visit(MakeCXCursor(Var, TU)))
1408 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001409 }
1410
Douglas Gregor263b47b2010-01-25 16:12:32 +00001411 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1412 return true;
1413 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1414 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001415
Douglas Gregor263b47b2010-01-25 16:12:32 +00001416 return false;
1417}
1418
1419bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1420 if (VarDecl *Var = S->getConditionVariable()) {
1421 if (Visit(MakeCXCursor(Var, TU)))
1422 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001423 }
1424
Douglas Gregor263b47b2010-01-25 16:12:32 +00001425 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1426 return true;
1427 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001428 return true;
1429
Douglas Gregor263b47b2010-01-25 16:12:32 +00001430 return false;
1431}
1432
1433bool CursorVisitor::VisitForStmt(ForStmt *S) {
1434 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1435 return true;
1436 if (VarDecl *Var = S->getConditionVariable()) {
1437 if (Visit(MakeCXCursor(Var, TU)))
1438 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001439 }
1440
Douglas Gregor263b47b2010-01-25 16:12:32 +00001441 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1442 return true;
1443 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1444 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001445 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1446 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001447
Douglas Gregorf5bab412010-01-22 01:00:11 +00001448 return false;
1449}
1450
Douglas Gregor8947a752010-09-02 20:35:02 +00001451bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1452 // Visit nested-name-specifier, if present.
1453 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1454 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1455 return true;
1456
1457 // Visit declaration name.
1458 if (VisitDeclarationNameInfo(E->getNameInfo()))
1459 return true;
1460
1461 // Visit explicitly-specified template arguments.
1462 if (E->hasExplicitTemplateArgs()) {
1463 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1464 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1465 *ArgEnd = Arg + Args.NumTemplateArgs;
1466 Arg != ArgEnd; ++Arg)
1467 if (VisitTemplateArgumentLoc(*Arg))
1468 return true;
1469 }
1470
1471 return false;
1472}
1473
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001474bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1475 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1476 return true;
1477
1478 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1479 return true;
1480
1481 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1482 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1483 return true;
1484
1485 return false;
1486}
1487
Ted Kremenek3064ef92010-08-27 21:34:58 +00001488bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1489 if (D->isDefinition()) {
1490 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1491 E = D->bases_end(); I != E; ++I) {
1492 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1493 return true;
1494 }
1495 }
1496
1497 return VisitTagDecl(D);
1498}
1499
1500
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001501bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1502 return Visit(B->getBlockDecl());
1503}
1504
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001505bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1506 // FIXME: Visit fields as well?
1507 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1508 return true;
1509
1510 return VisitExpr(E);
1511}
1512
Douglas Gregor336fd812010-01-23 00:40:08 +00001513bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1514 if (E->isArgumentType()) {
1515 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1516 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001517
Douglas Gregor336fd812010-01-23 00:40:08 +00001518 return false;
1519 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001520
Douglas Gregor336fd812010-01-23 00:40:08 +00001521 return VisitExpr(E);
1522}
1523
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001524bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1525 // Visit the base expression.
1526 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1527 return true;
1528
1529 // Visit the nested-name-specifier
1530 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1531 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1532 return true;
1533
1534 // Visit the declaration name.
1535 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1536 return true;
1537
1538 // Visit the explicitly-specified template arguments, if any.
1539 if (E->hasExplicitTemplateArgs()) {
1540 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1541 *ArgEnd = Arg + E->getNumTemplateArgs();
1542 Arg != ArgEnd;
1543 ++Arg) {
1544 if (VisitTemplateArgumentLoc(*Arg))
1545 return true;
1546 }
1547 }
1548
1549 return false;
1550}
1551
Douglas Gregor336fd812010-01-23 00:40:08 +00001552bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1553 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1554 if (Visit(TSInfo->getTypeLoc()))
1555 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001556
Douglas Gregor336fd812010-01-23 00:40:08 +00001557 return VisitCastExpr(E);
1558}
1559
1560bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1561 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1562 if (Visit(TSInfo->getTypeLoc()))
1563 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001564
Douglas Gregor336fd812010-01-23 00:40:08 +00001565 return VisitExpr(E);
1566}
1567
Douglas Gregor648220e2010-08-10 15:02:34 +00001568bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1569 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1570 Visit(E->getArgTInfo2()->getTypeLoc());
1571}
1572
1573bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1574 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1575 return true;
1576
1577 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1578}
1579
Douglas Gregor94802292010-09-02 21:20:16 +00001580bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1581 if (E->isTypeOperand()) {
1582 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1583 return Visit(TSInfo->getTypeLoc());
1584
1585 return false;
1586 }
1587
1588 return VisitExpr(E);
1589}
1590
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001591bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1592 if (E->isTypeOperand()) {
1593 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1594 return Visit(TSInfo->getTypeLoc());
1595
1596 return false;
1597 }
1598
1599 return VisitExpr(E);
1600}
1601
Douglas Gregorab6677e2010-09-08 00:15:04 +00001602bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1603 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1604 return Visit(TSInfo->getTypeLoc());
1605
1606 return VisitExpr(E);
1607}
1608
1609bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1610 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1611 return Visit(TSInfo->getTypeLoc());
1612
1613 return false;
1614}
1615
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001616bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1617 // Visit placement arguments.
1618 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1619 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1620 return true;
1621
1622 // Visit the allocated type.
1623 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1624 if (Visit(TSInfo->getTypeLoc()))
1625 return true;
1626
1627 // Visit the array size, if any.
1628 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1629 return true;
1630
1631 // Visit the initializer or constructor arguments.
1632 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1633 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1634 return true;
1635
1636 return false;
1637}
1638
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001639bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1640 // Visit base expression.
1641 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1642 return true;
1643
1644 // Visit the nested-name-specifier.
1645 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1646 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1647 return true;
1648
1649 // Visit the scope type that looks disturbingly like the nested-name-specifier
1650 // but isn't.
1651 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1652 if (Visit(TSInfo->getTypeLoc()))
1653 return true;
1654
1655 // Visit the name of the type being destroyed.
1656 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1657 if (Visit(TSInfo->getTypeLoc()))
1658 return true;
1659
1660 return false;
1661}
1662
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001663bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1664 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1665}
1666
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001667bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001668 // 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
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001677 // 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
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001688 // FIXME: We don't have a way to visit all of the declarations referenced
1689 // here.
1690 return false;
1691}
1692
Douglas Gregorbfebed22010-09-03 17:24:10 +00001693bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1694 DependentScopeDeclRefExpr *E) {
1695 // Visit the nested-name-specifier.
1696 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1697 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1698 return true;
1699
1700 // Visit the declaration name.
1701 if (VisitDeclarationNameInfo(E->getNameInfo()))
1702 return true;
1703
1704 // Visit the explicitly-specified template arguments.
1705 if (const ExplicitTemplateArgumentList *ArgList
1706 = E->getOptionalExplicitTemplateArgs()) {
1707 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1708 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1709 Arg != ArgEnd; ++Arg) {
1710 if (VisitTemplateArgumentLoc(*Arg))
1711 return true;
1712 }
1713 }
1714
1715 return false;
1716}
1717
Douglas Gregorab6677e2010-09-08 00:15:04 +00001718bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1719 CXXUnresolvedConstructExpr *E) {
1720 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1721 if (Visit(TSInfo->getTypeLoc()))
1722 return true;
1723
1724 return VisitExpr(E);
1725}
1726
Douglas Gregor25d63622010-09-03 17:35:34 +00001727bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1728 CXXDependentScopeMemberExpr *E) {
1729 // Visit the base expression, if there is one.
1730 if (!E->isImplicitAccess() &&
1731 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1732 return true;
1733
1734 // Visit the nested-name-specifier.
1735 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1736 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1737 return true;
1738
1739 // Visit the declaration name.
1740 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1741 return true;
1742
1743 // Visit the explicitly-specified template arguments.
1744 if (const ExplicitTemplateArgumentList *ArgList
1745 = E->getOptionalExplicitTemplateArgs()) {
1746 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1747 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1748 Arg != ArgEnd; ++Arg) {
1749 if (VisitTemplateArgumentLoc(*Arg))
1750 return true;
1751 }
1752 }
1753
1754 return false;
1755}
1756
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001757bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1758 // Visit the base expression, if there is one.
1759 if (!E->isImplicitAccess() &&
1760 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1761 return true;
1762
1763 return VisitOverloadExpr(E);
1764}
Douglas Gregor25d63622010-09-03 17:35:34 +00001765
Douglas Gregorc2350e52010-03-08 16:40:19 +00001766bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001767 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1768 if (Visit(TSInfo->getTypeLoc()))
1769 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001770
1771 return VisitExpr(E);
1772}
1773
Douglas Gregor81d34662010-04-20 15:39:42 +00001774bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1775 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1776}
1777
1778
Ted Kremenek09dfa372010-02-18 05:46:33 +00001779bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001780 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1781 i != e; ++i)
1782 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001783 return true;
1784
1785 return false;
1786}
1787
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001788extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001789CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1790 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001791 // We use crash recovery to make some of our APIs more reliable, implicitly
1792 // enable it.
1793 llvm::CrashRecoveryContext::Enable();
1794
Douglas Gregora030b7c2010-01-22 20:35:53 +00001795 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001796 if (excludeDeclarationsFromPCH)
1797 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001798 if (displayDiagnostics)
1799 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001800 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001801}
1802
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001803void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001804 if (CIdx)
1805 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001806 if (getenv("LIBCLANG_TIMING"))
1807 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001808}
1809
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001810void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001811 if (CIdx) {
1812 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1813 CXXIdx->setUseExternalASTGeneration(value);
1814 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001815}
1816
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001817CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001818 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001819 if (!CIdx)
1820 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001821
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001822 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001823
Douglas Gregor28019772010-04-05 23:52:57 +00001824 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001825 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001826 CXXIdx->getOnlyLocalDecls(),
1827 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001828}
1829
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001830unsigned clang_defaultEditingTranslationUnitOptions() {
1831 return CXTranslationUnit_PrecompiledPreamble;
1832}
1833
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001834CXTranslationUnit
1835clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1836 const char *source_filename,
1837 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001838 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001839 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001840 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001841 return clang_parseTranslationUnit(CIdx, source_filename,
1842 command_line_args, num_command_line_args,
1843 unsaved_files, num_unsaved_files,
1844 CXTranslationUnit_DetailedPreprocessingRecord);
1845}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001846
1847struct ParseTranslationUnitInfo {
1848 CXIndex CIdx;
1849 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001850 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001851 int num_command_line_args;
1852 struct CXUnsavedFile *unsaved_files;
1853 unsigned num_unsaved_files;
1854 unsigned options;
1855 CXTranslationUnit result;
1856};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001857static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001858 ParseTranslationUnitInfo *PTUI =
1859 static_cast<ParseTranslationUnitInfo*>(UserData);
1860 CXIndex CIdx = PTUI->CIdx;
1861 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001862 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001863 int num_command_line_args = PTUI->num_command_line_args;
1864 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1865 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1866 unsigned options = PTUI->options;
1867 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001868
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001869 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001870 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001871
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001872 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1873
Douglas Gregor44c181a2010-07-23 00:33:23 +00001874 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001875 bool CompleteTranslationUnit
1876 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001877 bool CacheCodeCompetionResults
1878 = options & CXTranslationUnit_CacheCompletionResults;
1879
Douglas Gregor5352ac02010-01-28 00:27:43 +00001880 // Configure the diagnostics.
1881 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001882 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1883 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001884
Douglas Gregor4db64a42010-01-23 00:14:00 +00001885 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1886 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001887 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001888 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001889 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001890 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1891 Buffer));
1892 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001893
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001894 if (!CXXIdx->getUseExternalASTGeneration()) {
1895 llvm::SmallVector<const char *, 16> Args;
1896
1897 // The 'source_filename' argument is optional. If the caller does not
1898 // specify it then it is assumed that the source file is specified
1899 // in the actual argument list.
1900 if (source_filename)
1901 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001902
1903 // Since the Clang C library is primarily used by batch tools dealing with
1904 // (often very broken) source code, where spell-checking can have a
1905 // significant negative impact on performance (particularly when
1906 // precompiled headers are involved), we disable it by default.
1907 // Note that we place this argument early in the list, so that it can be
1908 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001909 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001910
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001911 Args.insert(Args.end(), command_line_args,
1912 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001913
Douglas Gregor44c181a2010-07-23 00:33:23 +00001914 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001915 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1916 Args.push_back("-Xclang");
1917 Args.push_back("-detailed-preprocessing-record");
1918 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001919
Douglas Gregor5352ac02010-01-28 00:27:43 +00001920 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001921
Ted Kremenek29b72842010-01-07 22:49:05 +00001922#ifdef USE_CRASHTRACER
1923 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001924#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001925
Daniel Dunbar94220972009-12-05 02:17:18 +00001926 llvm::OwningPtr<ASTUnit> Unit(
1927 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001928 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001929 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001930 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001931 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001932 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001933 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001934 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001935 CompleteTranslationUnit,
1936 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001937
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001938 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001939 // Make sure to check that 'Unit' is non-NULL.
1940 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001941 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1942 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001943 D != DEnd; ++D) {
1944 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001945 CXString Msg = clang_formatDiagnostic(&Diag,
1946 clang_defaultDiagnosticDisplayOptions());
1947 fprintf(stderr, "%s\n", clang_getCString(Msg));
1948 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001949 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001950#ifdef LLVM_ON_WIN32
1951 // On Windows, force a flush, since there may be multiple copies of
1952 // stderr and stdout in the file system, all with different buffers
1953 // but writing to the same device.
1954 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001955#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001956 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001957 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001958
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001959 PTUI->result = Unit.take();
1960 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001961 }
1962
Ted Kremenek139ba862009-10-22 00:03:57 +00001963 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001964 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001965
Ted Kremenek139ba862009-10-22 00:03:57 +00001966 // First add the complete path to the 'clang' executable.
1967 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001968 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001969
Ted Kremenek139ba862009-10-22 00:03:57 +00001970 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001971 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001972
Ted Kremenek139ba862009-10-22 00:03:57 +00001973 // The 'source_filename' argument is optional. If the caller does not
1974 // specify it then it is assumed that the source file is specified
1975 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001976 if (source_filename)
1977 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001978
Steve Naroff37b5ac22009-10-15 20:50:09 +00001979 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001980 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001981 char astTmpFile[L_tmpnam];
1982 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001983
1984 // Since the Clang C library is primarily used by batch tools dealing with
1985 // (often very broken) source code, where spell-checking can have a
1986 // significant negative impact on performance (particularly when
1987 // precompiled headers are involved), we disable it by default.
1988 // Note that we place this argument early in the list, so that it can be
1989 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001990 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001991
Douglas Gregor4db64a42010-01-23 00:14:00 +00001992 // Remap any unsaved files to temporary files.
1993 std::vector<llvm::sys::Path> TemporaryFiles;
1994 std::vector<std::string> RemapArgs;
1995 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001996 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001997
Douglas Gregor4db64a42010-01-23 00:14:00 +00001998 // The pointers into the elements of RemapArgs are stable because we
1999 // won't be adding anything to RemapArgs after this point.
2000 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
2001 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002002
Ted Kremenek139ba862009-10-22 00:03:57 +00002003 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
2004 for (int i = 0; i < num_command_line_args; ++i)
2005 if (const char *arg = command_line_args[i]) {
2006 if (strcmp(arg, "-o") == 0) {
2007 ++i; // Also skip the matching argument.
2008 continue;
2009 }
2010 if (strcmp(arg, "-emit-ast") == 0 ||
2011 strcmp(arg, "-c") == 0 ||
2012 strcmp(arg, "-fsyntax-only") == 0) {
2013 continue;
2014 }
2015
2016 // Keep the argument.
2017 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002018 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002019
Douglas Gregord93256e2010-01-28 06:00:51 +00002020 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00002021 char tmpFileResults[L_tmpnam];
2022 char *tmpResultsFileName = tmpnam(tmpFileResults);
2023 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00002024 TemporaryFiles.push_back(DiagnosticsFile);
2025 argv.push_back("-fdiagnostics-binary");
2026
Douglas Gregor44c181a2010-07-23 00:33:23 +00002027 // Do we need the detailed preprocessing record?
2028 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2029 argv.push_back("-Xclang");
2030 argv.push_back("-detailed-preprocessing-record");
2031 }
2032
Ted Kremenek139ba862009-10-22 00:03:57 +00002033 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002034 argv.push_back(NULL);
2035
Ted Kremenekfeb15e32009-10-26 22:14:08 +00002036 // Invoke 'clang'.
2037 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
2038 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00002039 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00002040 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
2041 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00002042 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002043 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00002044 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002045
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002046 if (!ErrMsg.empty()) {
2047 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00002048 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002049 I != E; ++I) {
2050 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00002051 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002052 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00002053 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002054
Daniel Dunbar32141c82010-02-23 20:23:45 +00002055 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00002056 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00002057
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002058 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002059 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00002060 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00002061 RemappedFiles.size(),
2062 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00002063 if (ATU) {
2064 LoadSerializedDiagnostics(DiagnosticsFile,
2065 num_unsaved_files, unsaved_files,
2066 ATU->getFileManager(),
2067 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00002068 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002069 } else if (CXXIdx->getDisplayDiagnostics()) {
2070 // We failed to load the ASTUnit, but we can still deserialize the
2071 // diagnostics and emit them.
2072 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00002073 Diagnostic Diag;
2074 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002075 // FIXME: Faked LangOpts!
2076 LangOptions LangOpts;
2077 llvm::SmallVector<StoredDiagnostic, 4> Diags;
2078 LoadSerializedDiagnostics(DiagnosticsFile,
2079 num_unsaved_files, unsaved_files,
2080 FileMgr, SourceMgr, Diags);
2081 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
2082 DEnd = Diags.end();
2083 D != DEnd; ++D) {
2084 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00002085 CXString Msg = clang_formatDiagnostic(&Diag,
2086 clang_defaultDiagnosticDisplayOptions());
2087 fprintf(stderr, "%s\n", clang_getCString(Msg));
2088 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002089 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002090
2091#ifdef LLVM_ON_WIN32
2092 // On Windows, force a flush, since there may be multiple copies of
2093 // stderr and stdout in the file system, all with different buffers
2094 // but writing to the same device.
2095 fflush(stderr);
2096#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00002097 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002098
Douglas Gregor313e26c2010-02-18 23:35:40 +00002099 if (ATU) {
2100 // Make the translation unit responsible for destroying all temporary files.
2101 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2102 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002103 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00002104 } else {
2105 // Destroy all of the temporary files now; they can't be referenced any
2106 // longer.
2107 llvm::sys::Path(astTmpFile).eraseFromDisk();
2108 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2109 TemporaryFiles[i].eraseFromDisk();
2110 }
2111
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002112 PTUI->result = ATU;
2113}
2114CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2115 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002116 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002117 int num_command_line_args,
2118 struct CXUnsavedFile *unsaved_files,
2119 unsigned num_unsaved_files,
2120 unsigned options) {
2121 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2122 num_command_line_args, unsaved_files, num_unsaved_files,
2123 options, 0 };
2124 llvm::CrashRecoveryContext CRC;
2125
2126 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002127 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2128 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2129 fprintf(stderr, " 'command_line_args' : [");
2130 for (int i = 0; i != num_command_line_args; ++i) {
2131 if (i)
2132 fprintf(stderr, ", ");
2133 fprintf(stderr, "'%s'", command_line_args[i]);
2134 }
2135 fprintf(stderr, "],\n");
2136 fprintf(stderr, " 'unsaved_files' : [");
2137 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2138 if (i)
2139 fprintf(stderr, ", ");
2140 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2141 unsaved_files[i].Length);
2142 }
2143 fprintf(stderr, "],\n");
2144 fprintf(stderr, " 'options' : %d,\n", options);
2145 fprintf(stderr, "}\n");
2146
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002147 return 0;
2148 }
2149
2150 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002151}
2152
Douglas Gregor19998442010-08-13 15:35:05 +00002153unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2154 return CXSaveTranslationUnit_None;
2155}
2156
2157int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2158 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002159 if (!TU)
2160 return 1;
2161
2162 return static_cast<ASTUnit *>(TU)->Save(FileName);
2163}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002164
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002165void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002166 if (CTUnit) {
2167 // If the translation unit has been marked as unsafe to free, just discard
2168 // it.
2169 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2170 return;
2171
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002172 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002173 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002174}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002175
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002176unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2177 return CXReparse_None;
2178}
2179
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002180struct ReparseTranslationUnitInfo {
2181 CXTranslationUnit TU;
2182 unsigned num_unsaved_files;
2183 struct CXUnsavedFile *unsaved_files;
2184 unsigned options;
2185 int result;
2186};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002187static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002188 ReparseTranslationUnitInfo *RTUI =
2189 static_cast<ReparseTranslationUnitInfo*>(UserData);
2190 CXTranslationUnit TU = RTUI->TU;
2191 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2192 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2193 unsigned options = RTUI->options;
2194 (void) options;
2195 RTUI->result = 1;
2196
Douglas Gregorabc563f2010-07-19 21:46:24 +00002197 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002198 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002199
2200 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2201 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2202 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2203 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002204 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002205 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2206 Buffer));
2207 }
2208
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002209 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
2210 RemappedFiles.size()))
2211 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002212}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002213int clang_reparseTranslationUnit(CXTranslationUnit TU,
2214 unsigned num_unsaved_files,
2215 struct CXUnsavedFile *unsaved_files,
2216 unsigned options) {
2217 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2218 options, 0 };
2219 llvm::CrashRecoveryContext CRC;
2220
2221 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002222 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002223 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2224 return 1;
2225 }
2226
2227 return RTUI.result;
2228}
2229
Douglas Gregordf95a132010-08-09 20:45:32 +00002230
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002231CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002232 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002233 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002234
Steve Naroff77accc12009-09-03 18:19:54 +00002235 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002236 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002237}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002238
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002239CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002240 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002241 return Result;
2242}
2243
Ted Kremenekfb480492010-01-13 21:46:36 +00002244} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002245
Ted Kremenekfb480492010-01-13 21:46:36 +00002246//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002247// CXSourceLocation and CXSourceRange Operations.
2248//===----------------------------------------------------------------------===//
2249
Douglas Gregorb9790342010-01-22 21:44:22 +00002250extern "C" {
2251CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002252 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002253 return Result;
2254}
2255
2256unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002257 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2258 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2259 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002260}
2261
2262CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2263 CXFile file,
2264 unsigned line,
2265 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002266 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002267 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002268
Douglas Gregorb9790342010-01-22 21:44:22 +00002269 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2270 SourceLocation SLoc
2271 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002272 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002273 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002274
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002275 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002276}
2277
Douglas Gregor5352ac02010-01-28 00:27:43 +00002278CXSourceRange clang_getNullRange() {
2279 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2280 return Result;
2281}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002282
Douglas Gregor5352ac02010-01-28 00:27:43 +00002283CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2284 if (begin.ptr_data[0] != end.ptr_data[0] ||
2285 begin.ptr_data[1] != end.ptr_data[1])
2286 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002287
2288 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002289 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002290 return Result;
2291}
2292
Douglas Gregor46766dc2010-01-26 19:19:08 +00002293void clang_getInstantiationLocation(CXSourceLocation location,
2294 CXFile *file,
2295 unsigned *line,
2296 unsigned *column,
2297 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002298 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2299
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002300 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002301 if (file)
2302 *file = 0;
2303 if (line)
2304 *line = 0;
2305 if (column)
2306 *column = 0;
2307 if (offset)
2308 *offset = 0;
2309 return;
2310 }
2311
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002312 const SourceManager &SM =
2313 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002314 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002315
2316 if (file)
2317 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2318 if (line)
2319 *line = SM.getInstantiationLineNumber(InstLoc);
2320 if (column)
2321 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002322 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002323 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002324}
2325
Douglas Gregor1db19de2010-01-19 21:36:55 +00002326CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002327 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002328 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002329 return Result;
2330}
2331
2332CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002333 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002334 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002335 return Result;
2336}
2337
Douglas Gregorb9790342010-01-22 21:44:22 +00002338} // end: extern "C"
2339
Douglas Gregor1db19de2010-01-19 21:36:55 +00002340//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002341// CXFile Operations.
2342//===----------------------------------------------------------------------===//
2343
2344extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002345CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002346 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002347 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002348
Steve Naroff88145032009-10-27 14:35:18 +00002349 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002350 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002351}
2352
2353time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002354 if (!SFile)
2355 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002356
Steve Naroff88145032009-10-27 14:35:18 +00002357 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2358 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002359}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002360
Douglas Gregorb9790342010-01-22 21:44:22 +00002361CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2362 if (!tu)
2363 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002364
Douglas Gregorb9790342010-01-22 21:44:22 +00002365 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002366
Douglas Gregorb9790342010-01-22 21:44:22 +00002367 FileManager &FMgr = CXXUnit->getFileManager();
2368 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2369 return const_cast<FileEntry *>(File);
2370}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002371
Ted Kremenekfb480492010-01-13 21:46:36 +00002372} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002373
Ted Kremenekfb480492010-01-13 21:46:36 +00002374//===----------------------------------------------------------------------===//
2375// CXCursor Operations.
2376//===----------------------------------------------------------------------===//
2377
Ted Kremenekfb480492010-01-13 21:46:36 +00002378static Decl *getDeclFromExpr(Stmt *E) {
2379 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2380 return RefExpr->getDecl();
2381 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2382 return ME->getMemberDecl();
2383 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2384 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002385
Ted Kremenekfb480492010-01-13 21:46:36 +00002386 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2387 return getDeclFromExpr(CE->getCallee());
2388 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2389 return getDeclFromExpr(CE->getSubExpr());
2390 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2391 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002392
Ted Kremenekfb480492010-01-13 21:46:36 +00002393 return 0;
2394}
2395
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002396static SourceLocation getLocationFromExpr(Expr *E) {
2397 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2398 return /*FIXME:*/Msg->getLeftLoc();
2399 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2400 return DRE->getLocation();
2401 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2402 return Member->getMemberLoc();
2403 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2404 return Ivar->getLocation();
2405 return E->getLocStart();
2406}
2407
Ted Kremenekfb480492010-01-13 21:46:36 +00002408extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002409
2410unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002411 CXCursorVisitor visitor,
2412 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002413 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002414
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002415 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2416 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002417 return CursorVis.VisitChildren(parent);
2418}
2419
Douglas Gregor78205d42010-01-20 21:45:58 +00002420static CXString getDeclSpelling(Decl *D) {
2421 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2422 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002423 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002424
Douglas Gregor78205d42010-01-20 21:45:58 +00002425 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002426 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002427
Douglas Gregor78205d42010-01-20 21:45:58 +00002428 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2429 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2430 // and returns different names. NamedDecl returns the class name and
2431 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002432 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002433
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002434 if (isa<UsingDirectiveDecl>(D))
2435 return createCXString("");
2436
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002437 llvm::SmallString<1024> S;
2438 llvm::raw_svector_ostream os(S);
2439 ND->printName(os);
2440
2441 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002442}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002443
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002444CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002445 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002446 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002447
Steve Narofff334b4e2009-09-02 18:26:48 +00002448 if (clang_isReference(C.kind)) {
2449 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002450 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002451 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002452 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002453 }
2454 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002455 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002456 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002457 }
2458 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002459 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002460 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002461 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002462 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002463 case CXCursor_CXXBaseSpecifier: {
2464 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2465 return createCXString(B->getType().getAsString());
2466 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002467 case CXCursor_TypeRef: {
2468 TypeDecl *Type = getCursorTypeRef(C).first;
2469 assert(Type && "Missing type decl");
2470
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002471 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2472 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002473 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002474 case CXCursor_TemplateRef: {
2475 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002476 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002477
2478 return createCXString(Template->getNameAsString());
2479 }
Douglas Gregor69319002010-08-31 23:48:11 +00002480
2481 case CXCursor_NamespaceRef: {
2482 NamedDecl *NS = getCursorNamespaceRef(C).first;
2483 assert(NS && "Missing namespace decl");
2484
2485 return createCXString(NS->getNameAsString());
2486 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002487
Daniel Dunbaracca7252009-11-30 20:42:49 +00002488 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002489 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002490 }
2491 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002492
2493 if (clang_isExpression(C.kind)) {
2494 Decl *D = getDeclFromExpr(getCursorExpr(C));
2495 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002496 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002497 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002498 }
2499
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002500 if (C.kind == CXCursor_MacroInstantiation)
2501 return createCXString(getCursorMacroInstantiation(C)->getName()
2502 ->getNameStart());
2503
Douglas Gregor572feb22010-03-18 18:04:21 +00002504 if (C.kind == CXCursor_MacroDefinition)
2505 return createCXString(getCursorMacroDefinition(C)->getName()
2506 ->getNameStart());
2507
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002508 if (clang_isDeclaration(C.kind))
2509 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002510
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002511 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002512}
2513
Ted Kremeneke68fff62010-02-17 00:41:32 +00002514CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002515 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002516 case CXCursor_FunctionDecl:
2517 return createCXString("FunctionDecl");
2518 case CXCursor_TypedefDecl:
2519 return createCXString("TypedefDecl");
2520 case CXCursor_EnumDecl:
2521 return createCXString("EnumDecl");
2522 case CXCursor_EnumConstantDecl:
2523 return createCXString("EnumConstantDecl");
2524 case CXCursor_StructDecl:
2525 return createCXString("StructDecl");
2526 case CXCursor_UnionDecl:
2527 return createCXString("UnionDecl");
2528 case CXCursor_ClassDecl:
2529 return createCXString("ClassDecl");
2530 case CXCursor_FieldDecl:
2531 return createCXString("FieldDecl");
2532 case CXCursor_VarDecl:
2533 return createCXString("VarDecl");
2534 case CXCursor_ParmDecl:
2535 return createCXString("ParmDecl");
2536 case CXCursor_ObjCInterfaceDecl:
2537 return createCXString("ObjCInterfaceDecl");
2538 case CXCursor_ObjCCategoryDecl:
2539 return createCXString("ObjCCategoryDecl");
2540 case CXCursor_ObjCProtocolDecl:
2541 return createCXString("ObjCProtocolDecl");
2542 case CXCursor_ObjCPropertyDecl:
2543 return createCXString("ObjCPropertyDecl");
2544 case CXCursor_ObjCIvarDecl:
2545 return createCXString("ObjCIvarDecl");
2546 case CXCursor_ObjCInstanceMethodDecl:
2547 return createCXString("ObjCInstanceMethodDecl");
2548 case CXCursor_ObjCClassMethodDecl:
2549 return createCXString("ObjCClassMethodDecl");
2550 case CXCursor_ObjCImplementationDecl:
2551 return createCXString("ObjCImplementationDecl");
2552 case CXCursor_ObjCCategoryImplDecl:
2553 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002554 case CXCursor_CXXMethod:
2555 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002556 case CXCursor_UnexposedDecl:
2557 return createCXString("UnexposedDecl");
2558 case CXCursor_ObjCSuperClassRef:
2559 return createCXString("ObjCSuperClassRef");
2560 case CXCursor_ObjCProtocolRef:
2561 return createCXString("ObjCProtocolRef");
2562 case CXCursor_ObjCClassRef:
2563 return createCXString("ObjCClassRef");
2564 case CXCursor_TypeRef:
2565 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002566 case CXCursor_TemplateRef:
2567 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002568 case CXCursor_NamespaceRef:
2569 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002570 case CXCursor_UnexposedExpr:
2571 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002572 case CXCursor_BlockExpr:
2573 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002574 case CXCursor_DeclRefExpr:
2575 return createCXString("DeclRefExpr");
2576 case CXCursor_MemberRefExpr:
2577 return createCXString("MemberRefExpr");
2578 case CXCursor_CallExpr:
2579 return createCXString("CallExpr");
2580 case CXCursor_ObjCMessageExpr:
2581 return createCXString("ObjCMessageExpr");
2582 case CXCursor_UnexposedStmt:
2583 return createCXString("UnexposedStmt");
2584 case CXCursor_InvalidFile:
2585 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002586 case CXCursor_InvalidCode:
2587 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002588 case CXCursor_NoDeclFound:
2589 return createCXString("NoDeclFound");
2590 case CXCursor_NotImplemented:
2591 return createCXString("NotImplemented");
2592 case CXCursor_TranslationUnit:
2593 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002594 case CXCursor_UnexposedAttr:
2595 return createCXString("UnexposedAttr");
2596 case CXCursor_IBActionAttr:
2597 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002598 case CXCursor_IBOutletAttr:
2599 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002600 case CXCursor_IBOutletCollectionAttr:
2601 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002602 case CXCursor_PreprocessingDirective:
2603 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002604 case CXCursor_MacroDefinition:
2605 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002606 case CXCursor_MacroInstantiation:
2607 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002608 case CXCursor_Namespace:
2609 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002610 case CXCursor_LinkageSpec:
2611 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002612 case CXCursor_CXXBaseSpecifier:
2613 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002614 case CXCursor_Constructor:
2615 return createCXString("CXXConstructor");
2616 case CXCursor_Destructor:
2617 return createCXString("CXXDestructor");
2618 case CXCursor_ConversionFunction:
2619 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002620 case CXCursor_TemplateTypeParameter:
2621 return createCXString("TemplateTypeParameter");
2622 case CXCursor_NonTypeTemplateParameter:
2623 return createCXString("NonTypeTemplateParameter");
2624 case CXCursor_TemplateTemplateParameter:
2625 return createCXString("TemplateTemplateParameter");
2626 case CXCursor_FunctionTemplate:
2627 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002628 case CXCursor_ClassTemplate:
2629 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002630 case CXCursor_ClassTemplatePartialSpecialization:
2631 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002632 case CXCursor_NamespaceAlias:
2633 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002634 case CXCursor_UsingDirective:
2635 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002636 case CXCursor_UsingDeclaration:
2637 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002638 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002639
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002640 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002641 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002642}
Steve Naroff89922f82009-08-31 00:59:03 +00002643
Ted Kremeneke68fff62010-02-17 00:41:32 +00002644enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2645 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002646 CXClientData client_data) {
2647 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2648 *BestCursor = cursor;
2649 return CXChildVisit_Recurse;
2650}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002651
Douglas Gregorb9790342010-01-22 21:44:22 +00002652CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2653 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002654 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002655
Douglas Gregorb9790342010-01-22 21:44:22 +00002656 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002657 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2658
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002659 // Translate the given source location to make it point at the beginning of
2660 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002661 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002662
2663 // Guard against an invalid SourceLocation, or we may assert in one
2664 // of the following calls.
2665 if (SLoc.isInvalid())
2666 return clang_getNullCursor();
2667
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002668 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2669 CXXUnit->getASTContext().getLangOptions());
2670
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002671 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2672 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002673 // FIXME: Would be great to have a "hint" cursor, then walk from that
2674 // hint cursor upward until we find a cursor whose source range encloses
2675 // the region of interest, rather than starting from the translation unit.
2676 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002677 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002678 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002679 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002680 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002681 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002682}
2683
Ted Kremenek73885552009-11-17 19:28:59 +00002684CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002685 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002686}
2687
2688unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002689 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002690}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002691
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002692unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002693 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2694}
2695
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002696unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002697 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2698}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002699
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002700unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002701 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2702}
2703
Douglas Gregor97b98722010-01-19 23:20:36 +00002704unsigned clang_isExpression(enum CXCursorKind K) {
2705 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2706}
2707
2708unsigned clang_isStatement(enum CXCursorKind K) {
2709 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2710}
2711
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002712unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2713 return K == CXCursor_TranslationUnit;
2714}
2715
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002716unsigned clang_isPreprocessing(enum CXCursorKind K) {
2717 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2718}
2719
Ted Kremenekad6eff62010-03-08 21:17:29 +00002720unsigned clang_isUnexposed(enum CXCursorKind K) {
2721 switch (K) {
2722 case CXCursor_UnexposedDecl:
2723 case CXCursor_UnexposedExpr:
2724 case CXCursor_UnexposedStmt:
2725 case CXCursor_UnexposedAttr:
2726 return true;
2727 default:
2728 return false;
2729 }
2730}
2731
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002732CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002733 return C.kind;
2734}
2735
Douglas Gregor98258af2010-01-18 22:46:11 +00002736CXSourceLocation clang_getCursorLocation(CXCursor C) {
2737 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002738 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002739 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002740 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2741 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002742 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002743 }
2744
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002745 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002746 std::pair<ObjCProtocolDecl *, SourceLocation> P
2747 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002748 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002749 }
2750
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002751 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002752 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2753 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002754 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002755 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002756
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002757 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002758 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002759 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002760 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002761
2762 case CXCursor_TemplateRef: {
2763 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2764 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2765 }
2766
Douglas Gregor69319002010-08-31 23:48:11 +00002767 case CXCursor_NamespaceRef: {
2768 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2769 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2770 }
2771
Ted Kremenek3064ef92010-08-27 21:34:58 +00002772 case CXCursor_CXXBaseSpecifier: {
2773 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2774 return clang_getNullLocation();
2775 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002776
Douglas Gregorf46034a2010-01-18 23:41:10 +00002777 default:
2778 // FIXME: Need a way to enumerate all non-reference cases.
2779 llvm_unreachable("Missed a reference kind");
2780 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002781 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002782
2783 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002784 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002785 getLocationFromExpr(getCursorExpr(C)));
2786
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002787 if (C.kind == CXCursor_PreprocessingDirective) {
2788 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2789 return cxloc::translateSourceLocation(getCursorContext(C), L);
2790 }
Douglas Gregor48072312010-03-18 15:23:44 +00002791
2792 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002793 SourceLocation L
2794 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002795 return cxloc::translateSourceLocation(getCursorContext(C), L);
2796 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002797
2798 if (C.kind == CXCursor_MacroDefinition) {
2799 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2800 return cxloc::translateSourceLocation(getCursorContext(C), L);
2801 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002802
Ted Kremenek9a700d22010-05-12 06:16:13 +00002803 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002804 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002805
Douglas Gregorf46034a2010-01-18 23:41:10 +00002806 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002807 SourceLocation Loc = D->getLocation();
2808 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2809 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002810 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002811}
Douglas Gregora7bde202010-01-19 00:34:46 +00002812
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002813} // end extern "C"
2814
2815static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002816 if (clang_isReference(C.kind)) {
2817 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002818 case CXCursor_ObjCSuperClassRef:
2819 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002820
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002821 case CXCursor_ObjCProtocolRef:
2822 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002823
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002824 case CXCursor_ObjCClassRef:
2825 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002826
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002827 case CXCursor_TypeRef:
2828 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002829
2830 case CXCursor_TemplateRef:
2831 return getCursorTemplateRef(C).second;
2832
Douglas Gregor69319002010-08-31 23:48:11 +00002833 case CXCursor_NamespaceRef:
2834 return getCursorNamespaceRef(C).second;
2835
Ted Kremenek3064ef92010-08-27 21:34:58 +00002836 case CXCursor_CXXBaseSpecifier:
2837 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2838 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002839
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002840 default:
2841 // FIXME: Need a way to enumerate all non-reference cases.
2842 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002843 }
2844 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002845
2846 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002847 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002848
2849 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002850 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002851
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002852 if (C.kind == CXCursor_PreprocessingDirective)
2853 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002854
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002855 if (C.kind == CXCursor_MacroInstantiation)
2856 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002857
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002858 if (C.kind == CXCursor_MacroDefinition)
2859 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002860
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002861 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2862 return getCursorDecl(C)->getSourceRange();
2863
2864 return SourceRange();
2865}
2866
2867extern "C" {
2868
2869CXSourceRange clang_getCursorExtent(CXCursor C) {
2870 SourceRange R = getRawCursorExtent(C);
2871 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002872 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002873
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002874 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002875}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002876
2877CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002878 if (clang_isInvalid(C.kind))
2879 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002880
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002881 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002882 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002883 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002884
Douglas Gregor97b98722010-01-19 23:20:36 +00002885 if (clang_isExpression(C.kind)) {
2886 Decl *D = getDeclFromExpr(getCursorExpr(C));
2887 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002888 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002889 return clang_getNullCursor();
2890 }
2891
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002892 if (C.kind == CXCursor_MacroInstantiation) {
2893 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2894 return MakeMacroDefinitionCursor(Def, CXXUnit);
2895 }
2896
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002897 if (!clang_isReference(C.kind))
2898 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002899
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002900 switch (C.kind) {
2901 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002902 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002903
2904 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002905 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002906
2907 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002908 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002909
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002910 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002911 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002912
2913 case CXCursor_TemplateRef:
2914 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2915
Douglas Gregor69319002010-08-31 23:48:11 +00002916 case CXCursor_NamespaceRef:
2917 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2918
Ted Kremenek3064ef92010-08-27 21:34:58 +00002919 case CXCursor_CXXBaseSpecifier: {
2920 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2921 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2922 CXXUnit));
2923 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002924
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002925 default:
2926 // We would prefer to enumerate all non-reference cursor kinds here.
2927 llvm_unreachable("Unhandled reference cursor kind");
2928 break;
2929 }
2930 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002931
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002932 return clang_getNullCursor();
2933}
2934
Douglas Gregorb6998662010-01-19 19:34:47 +00002935CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002936 if (clang_isInvalid(C.kind))
2937 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002938
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002939 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002940
Douglas Gregorb6998662010-01-19 19:34:47 +00002941 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002942 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002943 C = clang_getCursorReferenced(C);
2944 WasReference = true;
2945 }
2946
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002947 if (C.kind == CXCursor_MacroInstantiation)
2948 return clang_getCursorReferenced(C);
2949
Douglas Gregorb6998662010-01-19 19:34:47 +00002950 if (!clang_isDeclaration(C.kind))
2951 return clang_getNullCursor();
2952
2953 Decl *D = getCursorDecl(C);
2954 if (!D)
2955 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002956
Douglas Gregorb6998662010-01-19 19:34:47 +00002957 switch (D->getKind()) {
2958 // Declaration kinds that don't really separate the notions of
2959 // declaration and definition.
2960 case Decl::Namespace:
2961 case Decl::Typedef:
2962 case Decl::TemplateTypeParm:
2963 case Decl::EnumConstant:
2964 case Decl::Field:
2965 case Decl::ObjCIvar:
2966 case Decl::ObjCAtDefsField:
2967 case Decl::ImplicitParam:
2968 case Decl::ParmVar:
2969 case Decl::NonTypeTemplateParm:
2970 case Decl::TemplateTemplateParm:
2971 case Decl::ObjCCategoryImpl:
2972 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002973 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002974 case Decl::LinkageSpec:
2975 case Decl::ObjCPropertyImpl:
2976 case Decl::FileScopeAsm:
2977 case Decl::StaticAssert:
2978 case Decl::Block:
2979 return C;
2980
2981 // Declaration kinds that don't make any sense here, but are
2982 // nonetheless harmless.
2983 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002984 break;
2985
2986 // Declaration kinds for which the definition is not resolvable.
2987 case Decl::UnresolvedUsingTypename:
2988 case Decl::UnresolvedUsingValue:
2989 break;
2990
2991 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002992 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2993 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002994
2995 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002996 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002997
2998 case Decl::Enum:
2999 case Decl::Record:
3000 case Decl::CXXRecord:
3001 case Decl::ClassTemplateSpecialization:
3002 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003003 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003004 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003005 return clang_getNullCursor();
3006
3007 case Decl::Function:
3008 case Decl::CXXMethod:
3009 case Decl::CXXConstructor:
3010 case Decl::CXXDestructor:
3011 case Decl::CXXConversion: {
3012 const FunctionDecl *Def = 0;
3013 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003014 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003015 return clang_getNullCursor();
3016 }
3017
3018 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003019 // Ask the variable if it has a definition.
3020 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3021 return MakeCXCursor(Def, CXXUnit);
3022 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003023 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003024
Douglas Gregorb6998662010-01-19 19:34:47 +00003025 case Decl::FunctionTemplate: {
3026 const FunctionDecl *Def = 0;
3027 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003028 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003029 return clang_getNullCursor();
3030 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003031
Douglas Gregorb6998662010-01-19 19:34:47 +00003032 case Decl::ClassTemplate: {
3033 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003034 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003035 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003036 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003037 return clang_getNullCursor();
3038 }
3039
3040 case Decl::Using: {
3041 UsingDecl *Using = cast<UsingDecl>(D);
3042 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003043 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
3044 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00003045 S != SEnd; ++S) {
3046 if (Def != clang_getNullCursor()) {
3047 // FIXME: We have no way to return multiple results.
3048 return clang_getNullCursor();
3049 }
3050
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003051 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003052 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003053 }
3054
3055 return Def;
3056 }
3057
3058 case Decl::UsingShadow:
3059 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003060 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003061 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003062
3063 case Decl::ObjCMethod: {
3064 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3065 if (Method->isThisDeclarationADefinition())
3066 return C;
3067
3068 // Dig out the method definition in the associated
3069 // @implementation, if we have it.
3070 // FIXME: The ASTs should make finding the definition easier.
3071 if (ObjCInterfaceDecl *Class
3072 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3073 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3074 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3075 Method->isInstanceMethod()))
3076 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003077 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003078
3079 return clang_getNullCursor();
3080 }
3081
3082 case Decl::ObjCCategory:
3083 if (ObjCCategoryImplDecl *Impl
3084 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003085 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003086 return clang_getNullCursor();
3087
3088 case Decl::ObjCProtocol:
3089 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3090 return C;
3091 return clang_getNullCursor();
3092
3093 case Decl::ObjCInterface:
3094 // There are two notions of a "definition" for an Objective-C
3095 // class: the interface and its implementation. When we resolved a
3096 // reference to an Objective-C class, produce the @interface as
3097 // the definition; when we were provided with the interface,
3098 // produce the @implementation as the definition.
3099 if (WasReference) {
3100 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3101 return C;
3102 } else if (ObjCImplementationDecl *Impl
3103 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003104 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003105 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003106
Douglas Gregorb6998662010-01-19 19:34:47 +00003107 case Decl::ObjCProperty:
3108 // FIXME: We don't really know where to find the
3109 // ObjCPropertyImplDecls that implement this property.
3110 return clang_getNullCursor();
3111
3112 case Decl::ObjCCompatibleAlias:
3113 if (ObjCInterfaceDecl *Class
3114 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3115 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003116 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003117
Douglas Gregorb6998662010-01-19 19:34:47 +00003118 return clang_getNullCursor();
3119
3120 case Decl::ObjCForwardProtocol: {
3121 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
3122 if (Forward->protocol_size() == 1)
3123 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003124 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003125 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003126
3127 // FIXME: Cannot return multiple definitions.
3128 return clang_getNullCursor();
3129 }
3130
3131 case Decl::ObjCClass: {
3132 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
3133 if (Class->size() == 1) {
3134 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
3135 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003136 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003137 return clang_getNullCursor();
3138 }
3139
3140 // FIXME: Cannot return multiple definitions.
3141 return clang_getNullCursor();
3142 }
3143
3144 case Decl::Friend:
3145 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003146 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003147 return clang_getNullCursor();
3148
3149 case Decl::FriendTemplate:
3150 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003151 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003152 return clang_getNullCursor();
3153 }
3154
3155 return clang_getNullCursor();
3156}
3157
3158unsigned clang_isCursorDefinition(CXCursor C) {
3159 if (!clang_isDeclaration(C.kind))
3160 return 0;
3161
3162 return clang_getCursorDefinition(C) == C;
3163}
3164
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003165void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003166 const char **startBuf,
3167 const char **endBuf,
3168 unsigned *startLine,
3169 unsigned *startColumn,
3170 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003171 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003172 assert(getCursorDecl(C) && "CXCursor has null decl");
3173 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003174 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3175 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003176
Steve Naroff4ade6d62009-09-23 17:52:52 +00003177 SourceManager &SM = FD->getASTContext().getSourceManager();
3178 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3179 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3180 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3181 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3182 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3183 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3184}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003185
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003186void clang_enableStackTraces(void) {
3187 llvm::sys::PrintStackTraceOnErrorSignal();
3188}
3189
Ted Kremenekfb480492010-01-13 21:46:36 +00003190} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003191
Ted Kremenekfb480492010-01-13 21:46:36 +00003192//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003193// Token-based Operations.
3194//===----------------------------------------------------------------------===//
3195
3196/* CXToken layout:
3197 * int_data[0]: a CXTokenKind
3198 * int_data[1]: starting token location
3199 * int_data[2]: token length
3200 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003201 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003202 * otherwise unused.
3203 */
3204extern "C" {
3205
3206CXTokenKind clang_getTokenKind(CXToken CXTok) {
3207 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3208}
3209
3210CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3211 switch (clang_getTokenKind(CXTok)) {
3212 case CXToken_Identifier:
3213 case CXToken_Keyword:
3214 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003215 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3216 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003217
3218 case CXToken_Literal: {
3219 // We have stashed the starting pointer in the ptr_data field. Use it.
3220 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003221 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003222 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003223
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003224 case CXToken_Punctuation:
3225 case CXToken_Comment:
3226 break;
3227 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003228
3229 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003230 // deconstructing the source location.
3231 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3232 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003233 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003234
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003235 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3236 std::pair<FileID, unsigned> LocInfo
3237 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003238 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003239 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003240 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3241 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003242 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003243
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003244 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003245}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003246
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003247CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3248 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3249 if (!CXXUnit)
3250 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003251
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003252 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3253 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3254}
3255
3256CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3257 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003258 if (!CXXUnit)
3259 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003260
3261 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003262 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3263}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003264
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003265void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3266 CXToken **Tokens, unsigned *NumTokens) {
3267 if (Tokens)
3268 *Tokens = 0;
3269 if (NumTokens)
3270 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003271
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003272 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3273 if (!CXXUnit || !Tokens || !NumTokens)
3274 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003275
Douglas Gregorbdf60622010-03-05 21:16:25 +00003276 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3277
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003278 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003279 if (R.isInvalid())
3280 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003281
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003282 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3283 std::pair<FileID, unsigned> BeginLocInfo
3284 = SourceMgr.getDecomposedLoc(R.getBegin());
3285 std::pair<FileID, unsigned> EndLocInfo
3286 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003287
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003288 // Cannot tokenize across files.
3289 if (BeginLocInfo.first != EndLocInfo.first)
3290 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003291
3292 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003293 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003294 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003295 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003296 if (Invalid)
3297 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003298
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003299 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3300 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003301 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003302 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003303
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003304 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003305 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003306 llvm::SmallVector<CXToken, 32> CXTokens;
3307 Token Tok;
3308 do {
3309 // Lex the next token
3310 Lex.LexFromRawLexer(Tok);
3311 if (Tok.is(tok::eof))
3312 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003313
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003314 // Initialize the CXToken.
3315 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003316
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003317 // - Common fields
3318 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3319 CXTok.int_data[2] = Tok.getLength();
3320 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003321
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003322 // - Kind-specific fields
3323 if (Tok.isLiteral()) {
3324 CXTok.int_data[0] = CXToken_Literal;
3325 CXTok.ptr_data = (void *)Tok.getLiteralData();
3326 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003327 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003328 std::pair<FileID, unsigned> LocInfo
3329 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003330 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003331 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003332 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3333 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003334 return;
3335
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003336 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003337 IdentifierInfo *II
3338 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003339
3340 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3341 CXTok.int_data[0] = CXToken_Keyword;
3342 }
3343 else {
3344 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3345 CXToken_Identifier
3346 : CXToken_Keyword;
3347 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003348 CXTok.ptr_data = II;
3349 } else if (Tok.is(tok::comment)) {
3350 CXTok.int_data[0] = CXToken_Comment;
3351 CXTok.ptr_data = 0;
3352 } else {
3353 CXTok.int_data[0] = CXToken_Punctuation;
3354 CXTok.ptr_data = 0;
3355 }
3356 CXTokens.push_back(CXTok);
3357 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003358
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003359 if (CXTokens.empty())
3360 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003361
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003362 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3363 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3364 *NumTokens = CXTokens.size();
3365}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003366
Ted Kremenek6db61092010-05-05 00:55:15 +00003367void clang_disposeTokens(CXTranslationUnit TU,
3368 CXToken *Tokens, unsigned NumTokens) {
3369 free(Tokens);
3370}
3371
3372} // end: extern "C"
3373
3374//===----------------------------------------------------------------------===//
3375// Token annotation APIs.
3376//===----------------------------------------------------------------------===//
3377
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003378typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003379static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3380 CXCursor parent,
3381 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003382namespace {
3383class AnnotateTokensWorker {
3384 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003385 CXToken *Tokens;
3386 CXCursor *Cursors;
3387 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003388 unsigned TokIdx;
3389 CursorVisitor AnnotateVis;
3390 SourceManager &SrcMgr;
3391
3392 bool MoreTokens() const { return TokIdx < NumTokens; }
3393 unsigned NextToken() const { return TokIdx; }
3394 void AdvanceToken() { ++TokIdx; }
3395 SourceLocation GetTokenLoc(unsigned tokI) {
3396 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3397 }
3398
Ted Kremenek6db61092010-05-05 00:55:15 +00003399public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003400 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003401 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3402 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003403 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003404 NumTokens(numTokens), TokIdx(0),
3405 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3406 Decl::MaxPCHLevel, RegionOfInterest),
3407 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003408
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003409 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003410 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003411 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003412};
3413}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003414
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003415void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3416 // Walk the AST within the region of interest, annotating tokens
3417 // along the way.
3418 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003419
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003420 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3421 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3422 if (Pos != Annotated.end())
3423 Cursors[I] = Pos->second;
3424 }
3425
3426 // Finish up annotating any tokens left.
3427 if (!MoreTokens())
3428 return;
3429
3430 const CXCursor &C = clang_getNullCursor();
3431 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3432 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3433 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003434 }
3435}
3436
Ted Kremenek6db61092010-05-05 00:55:15 +00003437enum CXChildVisitResult
3438AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003439 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3440 // We can always annotate a preprocessing directive/macro instantiation.
3441 if (clang_isPreprocessing(cursor.kind)) {
3442 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003443 return CXChildVisit_Recurse;
3444 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003445
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003446 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003447
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003448 if (cursorRange.isInvalid())
3449 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003450
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003451 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3452
Ted Kremeneka333c662010-05-12 05:29:33 +00003453 // Adjust the annotated range based specific declarations.
3454 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3455 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003456 Decl *D = cxcursor::getCursorDecl(cursor);
3457 // Don't visit synthesized ObjC methods, since they have no syntatic
3458 // representation in the source.
3459 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3460 if (MD->isSynthesized())
3461 return CXChildVisit_Continue;
3462 }
3463 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003464 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3465 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003466 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003467 if (TLoc.isValid() &&
3468 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003469 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003470 }
3471 }
3472 }
3473
Ted Kremenek3f404602010-08-14 01:14:06 +00003474 // If the location of the cursor occurs within a macro instantiation, record
3475 // the spelling location of the cursor in our annotation map. We can then
3476 // paper over the token labelings during a post-processing step to try and
3477 // get cursor mappings for tokens that are the *arguments* of a macro
3478 // instantiation.
3479 if (L.isMacroID()) {
3480 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3481 // Only invalidate the old annotation if it isn't part of a preprocessing
3482 // directive. Here we assume that the default construction of CXCursor
3483 // results in CXCursor.kind being an initialized value (i.e., 0). If
3484 // this isn't the case, we can fix by doing lookup + insertion.
3485
3486 CXCursor &oldC = Annotated[rawEncoding];
3487 if (!clang_isPreprocessing(oldC.kind))
3488 oldC = cursor;
3489 }
3490
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003491 const enum CXCursorKind K = clang_getCursorKind(parent);
3492 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003493 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3494 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003495
3496 while (MoreTokens()) {
3497 const unsigned I = NextToken();
3498 SourceLocation TokLoc = GetTokenLoc(I);
3499 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3500 case RangeBefore:
3501 Cursors[I] = updateC;
3502 AdvanceToken();
3503 continue;
3504 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003505 case RangeOverlap:
3506 break;
3507 }
3508 break;
3509 }
3510
3511 // Visit children to get their cursor information.
3512 const unsigned BeforeChildren = NextToken();
3513 VisitChildren(cursor);
3514 const unsigned AfterChildren = NextToken();
3515
3516 // Adjust 'Last' to the last token within the extent of the cursor.
3517 while (MoreTokens()) {
3518 const unsigned I = NextToken();
3519 SourceLocation TokLoc = GetTokenLoc(I);
3520 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3521 case RangeBefore:
3522 assert(0 && "Infeasible");
3523 case RangeAfter:
3524 break;
3525 case RangeOverlap:
3526 Cursors[I] = updateC;
3527 AdvanceToken();
3528 continue;
3529 }
3530 break;
3531 }
3532 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003533
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003534 // Scan the tokens that are at the beginning of the cursor, but are not
3535 // capture by the child cursors.
3536
3537 // For AST elements within macros, rely on a post-annotate pass to
3538 // to correctly annotate the tokens with cursors. Otherwise we can
3539 // get confusing results of having tokens that map to cursors that really
3540 // are expanded by an instantiation.
3541 if (L.isMacroID())
3542 cursor = clang_getNullCursor();
3543
3544 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3545 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3546 break;
3547 Cursors[I] = cursor;
3548 }
3549 // Scan the tokens that are at the end of the cursor, but are not captured
3550 // but the child cursors.
3551 for (unsigned I = AfterChildren; I != Last; ++I)
3552 Cursors[I] = cursor;
3553
3554 TokIdx = Last;
3555 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003556}
3557
Ted Kremenek6db61092010-05-05 00:55:15 +00003558static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3559 CXCursor parent,
3560 CXClientData client_data) {
3561 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3562}
3563
3564extern "C" {
3565
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003566void clang_annotateTokens(CXTranslationUnit TU,
3567 CXToken *Tokens, unsigned NumTokens,
3568 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003569
3570 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003571 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003572
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003573 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003574 if (!CXXUnit) {
3575 // Any token we don't specifically annotate will have a NULL cursor.
3576 const CXCursor &C = clang_getNullCursor();
3577 for (unsigned I = 0; I != NumTokens; ++I)
3578 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003579 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003580 }
3581
Douglas Gregorbdf60622010-03-05 21:16:25 +00003582 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003583
Douglas Gregor0396f462010-03-19 05:22:59 +00003584 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003585 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003586 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3587 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003588 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3589 clang_getTokenLocation(TU,
3590 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003591
Douglas Gregor0396f462010-03-19 05:22:59 +00003592 // A mapping from the source locations found when re-lexing or traversing the
3593 // region of interest to the corresponding cursors.
3594 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003595
3596 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003597 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003598 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3599 std::pair<FileID, unsigned> BeginLocInfo
3600 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3601 std::pair<FileID, unsigned> EndLocInfo
3602 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003603
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003604 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003605 bool Invalid = false;
3606 if (BeginLocInfo.first == EndLocInfo.first &&
3607 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3608 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003609 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3610 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003611 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003612 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003613 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003614
3615 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003616 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003617 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003618 Token Tok;
3619 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003620
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003621 reprocess:
3622 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3623 // We have found a preprocessing directive. Gobble it up so that we
3624 // don't see it while preprocessing these tokens later, but keep track of
3625 // all of the token locations inside this preprocessing directive so that
3626 // we can annotate them appropriately.
3627 //
3628 // FIXME: Some simple tests here could identify macro definitions and
3629 // #undefs, to provide specific cursor kinds for those.
3630 std::vector<SourceLocation> Locations;
3631 do {
3632 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003633 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003634 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003635
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003636 using namespace cxcursor;
3637 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003638 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3639 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003640 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003641 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3642 Annotated[Locations[I].getRawEncoding()] = Cursor;
3643 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003644
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003645 if (Tok.isAtStartOfLine())
3646 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003647
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003648 continue;
3649 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003650
Douglas Gregor48072312010-03-18 15:23:44 +00003651 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003652 break;
3653 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003654 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003655
Douglas Gregor0396f462010-03-19 05:22:59 +00003656 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003657 // a specific cursor.
3658 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3659 CXXUnit, RegionOfInterest);
3660 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003661}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003662} // end: extern "C"
3663
3664//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003665// Operations for querying linkage of a cursor.
3666//===----------------------------------------------------------------------===//
3667
3668extern "C" {
3669CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003670 if (!clang_isDeclaration(cursor.kind))
3671 return CXLinkage_Invalid;
3672
Ted Kremenek16b42592010-03-03 06:36:57 +00003673 Decl *D = cxcursor::getCursorDecl(cursor);
3674 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3675 switch (ND->getLinkage()) {
3676 case NoLinkage: return CXLinkage_NoLinkage;
3677 case InternalLinkage: return CXLinkage_Internal;
3678 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3679 case ExternalLinkage: return CXLinkage_External;
3680 };
3681
3682 return CXLinkage_Invalid;
3683}
3684} // end: extern "C"
3685
3686//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003687// Operations for querying language of a cursor.
3688//===----------------------------------------------------------------------===//
3689
3690static CXLanguageKind getDeclLanguage(const Decl *D) {
3691 switch (D->getKind()) {
3692 default:
3693 break;
3694 case Decl::ImplicitParam:
3695 case Decl::ObjCAtDefsField:
3696 case Decl::ObjCCategory:
3697 case Decl::ObjCCategoryImpl:
3698 case Decl::ObjCClass:
3699 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003700 case Decl::ObjCForwardProtocol:
3701 case Decl::ObjCImplementation:
3702 case Decl::ObjCInterface:
3703 case Decl::ObjCIvar:
3704 case Decl::ObjCMethod:
3705 case Decl::ObjCProperty:
3706 case Decl::ObjCPropertyImpl:
3707 case Decl::ObjCProtocol:
3708 return CXLanguage_ObjC;
3709 case Decl::CXXConstructor:
3710 case Decl::CXXConversion:
3711 case Decl::CXXDestructor:
3712 case Decl::CXXMethod:
3713 case Decl::CXXRecord:
3714 case Decl::ClassTemplate:
3715 case Decl::ClassTemplatePartialSpecialization:
3716 case Decl::ClassTemplateSpecialization:
3717 case Decl::Friend:
3718 case Decl::FriendTemplate:
3719 case Decl::FunctionTemplate:
3720 case Decl::LinkageSpec:
3721 case Decl::Namespace:
3722 case Decl::NamespaceAlias:
3723 case Decl::NonTypeTemplateParm:
3724 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003725 case Decl::TemplateTemplateParm:
3726 case Decl::TemplateTypeParm:
3727 case Decl::UnresolvedUsingTypename:
3728 case Decl::UnresolvedUsingValue:
3729 case Decl::Using:
3730 case Decl::UsingDirective:
3731 case Decl::UsingShadow:
3732 return CXLanguage_CPlusPlus;
3733 }
3734
3735 return CXLanguage_C;
3736}
3737
3738extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003739
3740enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3741 if (clang_isDeclaration(cursor.kind))
3742 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3743 if (D->hasAttr<UnavailableAttr>() ||
3744 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3745 return CXAvailability_Available;
3746
3747 if (D->hasAttr<DeprecatedAttr>())
3748 return CXAvailability_Deprecated;
3749 }
3750
3751 return CXAvailability_Available;
3752}
3753
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003754CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3755 if (clang_isDeclaration(cursor.kind))
3756 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3757
3758 return CXLanguage_Invalid;
3759}
3760} // end: extern "C"
3761
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003762
3763//===----------------------------------------------------------------------===//
3764// C++ AST instrospection.
3765//===----------------------------------------------------------------------===//
3766
3767extern "C" {
3768unsigned clang_CXXMethod_isStatic(CXCursor C) {
3769 if (!clang_isDeclaration(C.kind))
3770 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003771
3772 CXXMethodDecl *Method = 0;
3773 Decl *D = cxcursor::getCursorDecl(C);
3774 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3775 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3776 else
3777 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3778 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003779}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003780
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003781} // end: extern "C"
3782
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003783//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003784// Attribute introspection.
3785//===----------------------------------------------------------------------===//
3786
3787extern "C" {
3788CXType clang_getIBOutletCollectionType(CXCursor C) {
3789 if (C.kind != CXCursor_IBOutletCollectionAttr)
3790 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3791
3792 IBOutletCollectionAttr *A =
3793 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3794
3795 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3796}
3797} // end: extern "C"
3798
3799//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003800// CXString Operations.
3801//===----------------------------------------------------------------------===//
3802
3803extern "C" {
3804const char *clang_getCString(CXString string) {
3805 return string.Spelling;
3806}
3807
3808void clang_disposeString(CXString string) {
3809 if (string.MustFreeString && string.Spelling)
3810 free((void*)string.Spelling);
3811}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003812
Ted Kremenekfb480492010-01-13 21:46:36 +00003813} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003814
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003815namespace clang { namespace cxstring {
3816CXString createCXString(const char *String, bool DupString){
3817 CXString Str;
3818 if (DupString) {
3819 Str.Spelling = strdup(String);
3820 Str.MustFreeString = 1;
3821 } else {
3822 Str.Spelling = String;
3823 Str.MustFreeString = 0;
3824 }
3825 return Str;
3826}
3827
3828CXString createCXString(llvm::StringRef String, bool DupString) {
3829 CXString Result;
3830 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3831 char *Spelling = (char *)malloc(String.size() + 1);
3832 memmove(Spelling, String.data(), String.size());
3833 Spelling[String.size()] = 0;
3834 Result.Spelling = Spelling;
3835 Result.MustFreeString = 1;
3836 } else {
3837 Result.Spelling = String.data();
3838 Result.MustFreeString = 0;
3839 }
3840 return Result;
3841}
3842}}
3843
Ted Kremenek04bb7162010-01-22 22:44:15 +00003844//===----------------------------------------------------------------------===//
3845// Misc. utility functions.
3846//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003847
Ted Kremenek04bb7162010-01-22 22:44:15 +00003848extern "C" {
3849
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003850CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003851 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003852}
3853
3854} // end: extern "C"