blob: 966562def52c561ed41c6c2117a15a2e16b8c6f6 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000033#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor02465752009-10-16 21:24:31 +000034#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000035#include "llvm/Support/Timer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000036#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000037#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000038
Benjamin Kramerc2a98162010-03-13 21:22:49 +000039// Needed to define L_TMPNAM on some systems.
40#include <cstdio>
41
Steve Naroff50398192009-08-28 15:28:48 +000042using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000043using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000044using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000045
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000046//===----------------------------------------------------------------------===//
47// Crash Reporting.
48//===----------------------------------------------------------------------===//
49
Ted Kremenekd7ffd082010-05-22 00:06:46 +000050#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000051#include "clang/Analysis/Support/SaveAndRestore.h"
52// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000053static const char *__crashreporter_info__ = 0;
54asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000055#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000056static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000057static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000058static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
59static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
60
61static unsigned SetCrashTracerInfo(const char *str,
62 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000063
Ted Kremenek254ba7c2010-01-07 23:13:53 +000064 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000065 while (crashtracer_strings[slot]) {
66 if (++slot == NUM_CRASH_STRINGS)
67 slot = 0;
68 }
69 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000070 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000071
72 // We need to create an aggregate string because multiple threads
73 // may be in this method at one time. The crash reporter string
74 // will attempt to overapproximate the set of in-flight invocations
75 // of this function. Race conditions can still cause this goal
76 // to not be achieved.
77 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000078 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000079 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
80 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
81 }
82 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
83 return slot;
84}
85
86static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000087 unsigned max_slot = 0;
88 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000089
Ted Kremenek254ba7c2010-01-07 23:13:53 +000090 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
91
92 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
93 if (agg_crashtracer_strings[i] &&
94 crashtracer_counter_id[i] > max_value) {
95 max_slot = i;
96 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000097 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000098
99 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +0000100}
101
102namespace {
103class ArgsCrashTracerInfo {
104 llvm::SmallString<1024> CrashString;
105 llvm::SmallString<1024> AggregateString;
106 unsigned crashtracerSlot;
107public:
108 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
109 : crashtracerSlot(0)
110 {
111 {
112 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000113 Out << "ClangCIndex [" << getClangFullVersion() << "]"
114 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000115 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
116 E=Args.end(); I!=E; ++I)
117 Out << ' ' << *I;
118 }
119 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
120 AggregateString);
121 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000122
Ted Kremenek29b72842010-01-07 22:49:05 +0000123 ~ArgsCrashTracerInfo() {
124 ResetCrashTracerInfo(crashtracerSlot);
125 }
126};
127}
128#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000129
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000130/// \brief The result of comparing two source ranges.
131enum RangeComparisonResult {
132 /// \brief Either the ranges overlap or one of the ranges is invalid.
133 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135 /// \brief The first range ends before the second range starts.
136 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000137
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000138 /// \brief The first range starts after the second range ends.
139 RangeAfter
140};
141
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000142/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000143/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000144static RangeComparisonResult RangeCompare(SourceManager &SM,
145 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000146 SourceRange R2) {
147 assert(R1.isValid() && "First range is invalid?");
148 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000149 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000150 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000152 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000153 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000154 return RangeAfter;
155 return RangeOverlap;
156}
157
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000158/// \brief Determine if a source location falls within, before, or after a
159/// a given source range.
160static RangeComparisonResult LocationCompare(SourceManager &SM,
161 SourceLocation L, SourceRange R) {
162 assert(R.isValid() && "First range is invalid?");
163 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000164 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000165 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000166 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
167 return RangeBefore;
168 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
169 return RangeAfter;
170 return RangeOverlap;
171}
172
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000173/// \brief Translate a Clang source range into a CIndex source range.
174///
175/// Clang internally represents ranges where the end location points to the
176/// start of the token at the end. However, for external clients it is more
177/// useful to have a CXSourceRange be a proper half-open interval. This routine
178/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000179CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000180 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000181 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000182 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000183 // location accordingly.
184 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000185 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000186 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000187 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000188 EndLoc = EndLoc.getFileLocWithOffset(Length);
189 }
190
191 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
192 R.getBegin().getRawEncoding(),
193 EndLoc.getRawEncoding() };
194 return Result;
195}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000196
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000197//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000198// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000199//===----------------------------------------------------------------------===//
200
Steve Naroff89922f82009-08-31 00:59:03 +0000201namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000202
Douglas Gregorb1373d02010-01-20 20:59:29 +0000203// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000205 public TypeLocVisitor<CursorVisitor, bool>,
206 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000207{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000209 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000211 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000212 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000213
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000214 /// \brief The declaration that serves at the parent of any statement or
215 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000216 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000217
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000219 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000221 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000222 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000223
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000224 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
225 // to the visitor. Declarations with a PCH level greater than this value will
226 // be suppressed.
227 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000228
229 /// \brief When valid, a source range to which the cursor should restrict
230 /// its search.
231 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000232
Douglas Gregorb1373d02010-01-20 20:59:29 +0000233 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000234 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000235 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000236
237 /// \brief Determine whether this particular source range comes before, comes
238 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000239 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000240 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000241 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
242
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000243 class SetParentRAII {
244 CXCursor &Parent;
245 Decl *&StmtParent;
246 CXCursor OldParent;
247
248 public:
249 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
250 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
251 {
252 Parent = NewParent;
253 if (clang_isDeclaration(Parent.kind))
254 StmtParent = getCursorDecl(Parent);
255 }
256
257 ~SetParentRAII() {
258 Parent = OldParent;
259 if (clang_isDeclaration(Parent.kind))
260 StmtParent = getCursorDecl(Parent);
261 }
262 };
263
Steve Naroff89922f82009-08-31 00:59:03 +0000264public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000265 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
266 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000267 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000268 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000269 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000270 {
271 Parent.kind = CXCursor_NoDeclFound;
272 Parent.data[0] = 0;
273 Parent.data[1] = 0;
274 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000275 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000276 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000277
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000278 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000279
280 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
281 getPreprocessedEntities();
282
Douglas Gregorb1373d02010-01-20 20:59:29 +0000283 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000284
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000285 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000286 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000287 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000288 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000289 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000290 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
291 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000292 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000293 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000294 bool VisitClassTemplatePartialSpecializationDecl(
295 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000296 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000297 bool VisitEnumConstantDecl(EnumConstantDecl *D);
298 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
299 bool VisitFunctionDecl(FunctionDecl *ND);
300 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000301 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000302 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000303 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000304 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000305 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000306 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
307 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
308 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
309 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000310 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000311 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
312 bool VisitObjCImplDecl(ObjCImplDecl *D);
313 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
314 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
315 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
316 // etc.
317 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
318 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
319 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000320 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000321 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000322 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000323 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000324 bool VisitUsingDecl(UsingDecl *D);
325 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
326 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000327
Douglas Gregor01829d32010-08-31 14:41:23 +0000328 // Name visitor
329 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
330
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000331 // Template visitors
332 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000333 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000334 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
335
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000336 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000337 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000338 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000339 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000340 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
341 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000342 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000343 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000344 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000345 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
346 bool VisitPointerTypeLoc(PointerTypeLoc TL);
347 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
348 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
349 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
350 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000351 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000352 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000353 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000354 // FIXME: Implement visitors here when the unimplemented TypeLocs get
355 // implemented
356 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
357 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000358
Douglas Gregora59e3902010-01-21 23:27:09 +0000359 // Statement visitors
360 bool VisitStmt(Stmt *S);
361 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000362 // FIXME: LabelStmt label?
363 bool VisitIfStmt(IfStmt *S);
364 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000365 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000366 bool VisitWhileStmt(WhileStmt *S);
367 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000368// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000369
Douglas Gregor336fd812010-01-23 00:40:08 +0000370 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000371 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
372 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000373 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000374 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000375 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000376 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000377 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000378 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000379 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000380 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000381 // FIXME: AddrLabelExpr (once we have cursors for labels)
382 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
383 bool VisitVAArgExpr(VAArgExpr *E);
384 // FIXME: InitListExpr (for the designators)
385 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000386};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000387
Ted Kremenekab188932010-01-05 19:32:54 +0000388} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000389
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000390static SourceRange getRawCursorExtent(CXCursor C);
391
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000393 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
394}
395
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396/// \brief Visit the given cursor and, if requested by the visitor,
397/// its children.
398///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000399/// \param Cursor the cursor to visit.
400///
401/// \param CheckRegionOfInterest if true, then the caller already checked that
402/// this cursor is within the region of interest.
403///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000404/// \returns true if the visitation should be aborted, false if it
405/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000406bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407 if (clang_isInvalid(Cursor.kind))
408 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000409
Douglas Gregorb1373d02010-01-20 20:59:29 +0000410 if (clang_isDeclaration(Cursor.kind)) {
411 Decl *D = getCursorDecl(Cursor);
412 assert(D && "Invalid declaration cursor");
413 if (D->getPCHLevel() > MaxPCHLevel)
414 return false;
415
416 if (D->isImplicit())
417 return false;
418 }
419
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000420 // If we have a range of interest, and this cursor doesn't intersect with it,
421 // we're done.
422 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000423 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000424 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000425 return false;
426 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000427
Douglas Gregorb1373d02010-01-20 20:59:29 +0000428 switch (Visitor(Cursor, Parent, ClientData)) {
429 case CXChildVisit_Break:
430 return true;
431
432 case CXChildVisit_Continue:
433 return false;
434
435 case CXChildVisit_Recurse:
436 return VisitChildren(Cursor);
437 }
438
Douglas Gregorfd643772010-01-25 16:45:46 +0000439 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440}
441
Douglas Gregor788f5a12010-03-20 00:41:21 +0000442std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
443CursorVisitor::getPreprocessedEntities() {
444 PreprocessingRecord &PPRec
445 = *TU->getPreprocessor().getPreprocessingRecord();
446
447 bool OnlyLocalDecls
448 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
449
450 // There is no region of interest; we have to walk everything.
451 if (RegionOfInterest.isInvalid())
452 return std::make_pair(PPRec.begin(OnlyLocalDecls),
453 PPRec.end(OnlyLocalDecls));
454
455 // Find the file in which the region of interest lands.
456 SourceManager &SM = TU->getSourceManager();
457 std::pair<FileID, unsigned> Begin
458 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
459 std::pair<FileID, unsigned> End
460 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
461
462 // The region of interest spans files; we have to walk everything.
463 if (Begin.first != End.first)
464 return std::make_pair(PPRec.begin(OnlyLocalDecls),
465 PPRec.end(OnlyLocalDecls));
466
467 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
468 = TU->getPreprocessedEntitiesByFile();
469 if (ByFileMap.empty()) {
470 // Build the mapping from files to sets of preprocessed entities.
471 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
472 EEnd = PPRec.end(OnlyLocalDecls);
473 E != EEnd; ++E) {
474 std::pair<FileID, unsigned> P
475 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
476 ByFileMap[P.first].push_back(*E);
477 }
478 }
479
480 return std::make_pair(ByFileMap[Begin.first].begin(),
481 ByFileMap[Begin.first].end());
482}
483
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484/// \brief Visit the children of the given cursor.
485///
486/// \returns true if the visitation should be aborted, false if it
487/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000488bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000489 if (clang_isReference(Cursor.kind)) {
490 // By definition, references have no children.
491 return false;
492 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000493
494 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000496 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000497
Douglas Gregorb1373d02010-01-20 20:59:29 +0000498 if (clang_isDeclaration(Cursor.kind)) {
499 Decl *D = getCursorDecl(Cursor);
500 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000501 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000502 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000503
Douglas Gregora59e3902010-01-21 23:27:09 +0000504 if (clang_isStatement(Cursor.kind))
505 return Visit(getCursorStmt(Cursor));
506 if (clang_isExpression(Cursor.kind))
507 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000508
Douglas Gregorb1373d02010-01-20 20:59:29 +0000509 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000510 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000511 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
512 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000513 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
514 TLEnd = CXXUnit->top_level_end();
515 TL != TLEnd; ++TL) {
516 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000517 return true;
518 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000519 } else if (VisitDeclContext(
520 CXXUnit->getASTContext().getTranslationUnitDecl()))
521 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000522
Douglas Gregor0396f462010-03-19 05:22:59 +0000523 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000524 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000525 // FIXME: Once we have the ability to deserialize a preprocessing record,
526 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000527 PreprocessingRecord::iterator E, EEnd;
528 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000529 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
530 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
531 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000532
Douglas Gregor0396f462010-03-19 05:22:59 +0000533 continue;
534 }
535
536 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
537 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
538 return true;
539
540 continue;
541 }
542 }
543 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000544 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000545 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000546
Douglas Gregorb1373d02010-01-20 20:59:29 +0000547 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000548 return false;
549}
550
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000551bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000552 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
553 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000554
Ted Kremenek664cffd2010-07-22 11:30:19 +0000555 if (Stmt *Body = B->getBody())
556 return Visit(MakeCXCursor(Body, StmtParent, TU));
557
558 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000559}
560
Douglas Gregorb1373d02010-01-20 20:59:29 +0000561bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000562 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000563 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000564
Ted Kremenek23173d72010-05-18 21:09:07 +0000565 Decl *D = *I;
566 if (D->getLexicalDeclContext() != DC)
567 continue;
568
569 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000570
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000571 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000572 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000573 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000574 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000575
576 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000577 case RangeBefore:
578 // This declaration comes before the region of interest; skip it.
579 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000580
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000581 case RangeAfter:
582 // This declaration comes after the region of interest; we're done.
583 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000584
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000585 case RangeOverlap:
586 // This declaration overlaps the region of interest; visit it.
587 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000588 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000589 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000590
Daniel Dunbard52864b2010-02-14 10:02:57 +0000591 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000592 return true;
593 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000594
Douglas Gregorb1373d02010-01-20 20:59:29 +0000595 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000596}
597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
599 llvm_unreachable("Translation units are visited directly by Visit()");
600 return false;
601}
602
603bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
604 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
605 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000606
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000607 return false;
608}
609
610bool CursorVisitor::VisitTagDecl(TagDecl *D) {
611 return VisitDeclContext(D);
612}
613
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000614bool CursorVisitor::VisitClassTemplateSpecializationDecl(
615 ClassTemplateSpecializationDecl *D) {
616 bool ShouldVisitBody = false;
617 switch (D->getSpecializationKind()) {
618 case TSK_Undeclared:
619 case TSK_ImplicitInstantiation:
620 // Nothing to visit
621 return false;
622
623 case TSK_ExplicitInstantiationDeclaration:
624 case TSK_ExplicitInstantiationDefinition:
625 break;
626
627 case TSK_ExplicitSpecialization:
628 ShouldVisitBody = true;
629 break;
630 }
631
632 // Visit the template arguments used in the specialization.
633 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
634 TypeLoc TL = SpecType->getTypeLoc();
635 if (TemplateSpecializationTypeLoc *TSTLoc
636 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
637 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
638 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
639 return true;
640 }
641 }
642
643 if (ShouldVisitBody && VisitCXXRecordDecl(D))
644 return true;
645
646 return false;
647}
648
Douglas Gregor74dbe642010-08-31 19:31:58 +0000649bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
650 ClassTemplatePartialSpecializationDecl *D) {
651 // FIXME: Visit the "outer" template parameter lists on the TagDecl
652 // before visiting these template parameters.
653 if (VisitTemplateParameters(D->getTemplateParameters()))
654 return true;
655
656 // Visit the partial specialization arguments.
657 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
658 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
659 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
660 return true;
661
662 return VisitCXXRecordDecl(D);
663}
664
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000665bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000666 // Visit the default argument.
667 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
668 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
669 if (Visit(DefArg->getTypeLoc()))
670 return true;
671
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000672 return false;
673}
674
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000675bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
676 if (Expr *Init = D->getInitExpr())
677 return Visit(MakeCXCursor(Init, StmtParent, TU));
678 return false;
679}
680
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000681bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
682 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
683 if (Visit(TSInfo->getTypeLoc()))
684 return true;
685
686 return false;
687}
688
Douglas Gregorb1373d02010-01-20 20:59:29 +0000689bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000690 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
691 // Visit the function declaration's syntactic components in the order
692 // written. This requires a bit of work.
693 TypeLoc TL = TSInfo->getTypeLoc();
694 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
695
696 // If we have a function declared directly (without the use of a typedef),
697 // visit just the return type. Otherwise, just visit the function's type
698 // now.
699 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
700 (!FTL && Visit(TL)))
701 return true;
702
703 // FIXME: Visit the nested-name-specifier, if present.
704
705 // Visit the declaration name.
706 if (VisitDeclarationNameInfo(ND->getNameInfo()))
707 return true;
708
709 // FIXME: Visit explicitly-specified template arguments!
710
711 // Visit the function parameters, if we have a function type.
712 if (FTL && VisitFunctionTypeLoc(*FTL, true))
713 return true;
714
715 // FIXME: Attributes?
716 }
717
Douglas Gregora59e3902010-01-21 23:27:09 +0000718 if (ND->isThisDeclarationADefinition() &&
719 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
720 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000721
Douglas Gregorb1373d02010-01-20 20:59:29 +0000722 return false;
723}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000724
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000725bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
726 if (VisitDeclaratorDecl(D))
727 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000728
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000729 if (Expr *BitWidth = D->getBitWidth())
730 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000731
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000732 return false;
733}
734
735bool CursorVisitor::VisitVarDecl(VarDecl *D) {
736 if (VisitDeclaratorDecl(D))
737 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000738
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000739 if (Expr *Init = D->getInit())
740 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000741
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000742 return false;
743}
744
Douglas Gregor84b51d72010-09-01 20:16:53 +0000745bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
746 if (VisitDeclaratorDecl(D))
747 return true;
748
749 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
750 if (Expr *DefArg = D->getDefaultArgument())
751 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
752
753 return false;
754}
755
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000756bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
757 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
758 // before visiting these template parameters.
759 if (VisitTemplateParameters(D->getTemplateParameters()))
760 return true;
761
762 return VisitFunctionDecl(D->getTemplatedDecl());
763}
764
Douglas Gregor39d6f072010-08-31 19:02:00 +0000765bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
766 // FIXME: Visit the "outer" template parameter lists on the TagDecl
767 // before visiting these template parameters.
768 if (VisitTemplateParameters(D->getTemplateParameters()))
769 return true;
770
771 return VisitCXXRecordDecl(D->getTemplatedDecl());
772}
773
Douglas Gregor84b51d72010-09-01 20:16:53 +0000774bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
775 if (VisitTemplateParameters(D->getTemplateParameters()))
776 return true;
777
778 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
779 VisitTemplateArgumentLoc(D->getDefaultArgument()))
780 return true;
781
782 return false;
783}
784
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000785bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000786 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
787 if (Visit(TSInfo->getTypeLoc()))
788 return true;
789
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000790 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000791 PEnd = ND->param_end();
792 P != PEnd; ++P) {
793 if (Visit(MakeCXCursor(*P, TU)))
794 return true;
795 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797 if (ND->isThisDeclarationADefinition() &&
798 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
799 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000800
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000801 return false;
802}
803
Douglas Gregora59e3902010-01-21 23:27:09 +0000804bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
805 return VisitDeclContext(D);
806}
807
Douglas Gregorb1373d02010-01-20 20:59:29 +0000808bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000809 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
810 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000811 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000812
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000813 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
814 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
815 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000816 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000817 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000818
Douglas Gregora59e3902010-01-21 23:27:09 +0000819 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000820}
821
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000822bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
823 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
824 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
825 E = PID->protocol_end(); I != E; ++I, ++PL)
826 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
827 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000828
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000829 return VisitObjCContainerDecl(PID);
830}
831
Ted Kremenek23173d72010-05-18 21:09:07 +0000832bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000833 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
834 return true;
835
Ted Kremenek23173d72010-05-18 21:09:07 +0000836 // FIXME: This implements a workaround with @property declarations also being
837 // installed in the DeclContext for the @interface. Eventually this code
838 // should be removed.
839 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
840 if (!CDecl || !CDecl->IsClassExtension())
841 return false;
842
843 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
844 if (!ID)
845 return false;
846
847 IdentifierInfo *PropertyId = PD->getIdentifier();
848 ObjCPropertyDecl *prevDecl =
849 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
850
851 if (!prevDecl)
852 return false;
853
854 // Visit synthesized methods since they will be skipped when visiting
855 // the @interface.
856 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
857 if (MD->isSynthesized())
858 if (Visit(MakeCXCursor(MD, TU)))
859 return true;
860
861 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
862 if (MD->isSynthesized())
863 if (Visit(MakeCXCursor(MD, TU)))
864 return true;
865
866 return false;
867}
868
Douglas Gregorb1373d02010-01-20 20:59:29 +0000869bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000870 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000871 if (D->getSuperClass() &&
872 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000873 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000874 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000875 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000876
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000877 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
878 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
879 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000880 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000881 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000882
Douglas Gregora59e3902010-01-21 23:27:09 +0000883 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000884}
885
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000886bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
887 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000888}
889
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000890bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000891 // 'ID' could be null when dealing with invalid code.
892 if (ObjCInterfaceDecl *ID = D->getClassInterface())
893 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
894 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000895
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000896 return VisitObjCImplDecl(D);
897}
898
899bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
900#if 0
901 // Issue callbacks for super class.
902 // FIXME: No source location information!
903 if (D->getSuperClass() &&
904 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000905 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000906 TU)))
907 return true;
908#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000909
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000910 return VisitObjCImplDecl(D);
911}
912
913bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
914 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
915 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
916 E = D->protocol_end();
917 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000918 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000919 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000920
921 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000922}
923
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000924bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
925 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
926 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
927 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000928
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000929 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000930}
931
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000932bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
933 return VisitDeclContext(D);
934}
935
Douglas Gregor69319002010-08-31 23:48:11 +0000936bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregor7e242562010-09-01 19:52:22 +0000937 // FIXME: Visit nested-name-specifier.
Douglas Gregor69319002010-08-31 23:48:11 +0000938
939 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
940 D->getTargetNameLoc(), TU));
941}
942
Douglas Gregor7e242562010-09-01 19:52:22 +0000943bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
944 // FIXME: Visit nested-name-specifier.
945
946 // FIXME: Provide a multi-reference of some kind for all of the declarations
947 // that the using declaration refers to. We don't have this kind of cursor
948 // yet.
949
950 return VisitDeclarationNameInfo(D->getNameInfo());
951}
952
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000953bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor7e242562010-09-01 19:52:22 +0000954 // FIXME: Visit nested-name-specifier.
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000955
956 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
957 D->getIdentLocation(), TU));
958}
959
Douglas Gregor7e242562010-09-01 19:52:22 +0000960bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
961 // FIXME: Visit nested-name-specifier.
962
963 return VisitDeclarationNameInfo(D->getNameInfo());
964}
965
966bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
967 UnresolvedUsingTypenameDecl *D) {
968 // FIXME: Visit nested-name-specifier.
969 return false;
970}
971
Douglas Gregor01829d32010-08-31 14:41:23 +0000972bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
973 switch (Name.getName().getNameKind()) {
974 case clang::DeclarationName::Identifier:
975 case clang::DeclarationName::CXXLiteralOperatorName:
976 case clang::DeclarationName::CXXOperatorName:
977 case clang::DeclarationName::CXXUsingDirective:
978 return false;
979
980 case clang::DeclarationName::CXXConstructorName:
981 case clang::DeclarationName::CXXDestructorName:
982 case clang::DeclarationName::CXXConversionFunctionName:
983 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
984 return Visit(TSInfo->getTypeLoc());
985 return false;
986
987 case clang::DeclarationName::ObjCZeroArgSelector:
988 case clang::DeclarationName::ObjCOneArgSelector:
989 case clang::DeclarationName::ObjCMultiArgSelector:
990 // FIXME: Per-identifier location info?
991 return false;
992 }
993
994 return false;
995}
996
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000997bool CursorVisitor::VisitTemplateParameters(
998 const TemplateParameterList *Params) {
999 if (!Params)
1000 return false;
1001
1002 for (TemplateParameterList::const_iterator P = Params->begin(),
1003 PEnd = Params->end();
1004 P != PEnd; ++P) {
1005 if (Visit(MakeCXCursor(*P, TU)))
1006 return true;
1007 }
1008
1009 return false;
1010}
1011
Douglas Gregor0b36e612010-08-31 20:37:03 +00001012bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1013 switch (Name.getKind()) {
1014 case TemplateName::Template:
1015 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1016
1017 case TemplateName::OverloadedTemplate:
1018 // FIXME: We need a way to return multiple lookup results in a single
1019 // cursor.
1020 return false;
1021
1022 case TemplateName::DependentTemplate:
1023 // FIXME: Visit nested-name-specifier.
1024 return false;
1025
1026 case TemplateName::QualifiedTemplate:
1027 // FIXME: Visit nested-name-specifier.
1028 return Visit(MakeCursorTemplateRef(
1029 Name.getAsQualifiedTemplateName()->getDecl(),
1030 Loc, TU));
1031 }
1032
1033 return false;
1034}
1035
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001036bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1037 switch (TAL.getArgument().getKind()) {
1038 case TemplateArgument::Null:
1039 case TemplateArgument::Integral:
1040 return false;
1041
1042 case TemplateArgument::Pack:
1043 // FIXME: Implement when variadic templates come along.
1044 return false;
1045
1046 case TemplateArgument::Type:
1047 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1048 return Visit(TSInfo->getTypeLoc());
1049 return false;
1050
1051 case TemplateArgument::Declaration:
1052 if (Expr *E = TAL.getSourceDeclExpression())
1053 return Visit(MakeCXCursor(E, StmtParent, TU));
1054 return false;
1055
1056 case TemplateArgument::Expression:
1057 if (Expr *E = TAL.getSourceExpression())
1058 return Visit(MakeCXCursor(E, StmtParent, TU));
1059 return false;
1060
1061 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001062 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1063 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001064 }
1065
1066 return false;
1067}
1068
Ted Kremeneka0536d82010-05-07 01:04:29 +00001069bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1070 return VisitDeclContext(D);
1071}
1072
Douglas Gregor01829d32010-08-31 14:41:23 +00001073bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1074 return Visit(TL.getUnqualifiedLoc());
1075}
1076
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001077bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1078 ASTContext &Context = TU->getASTContext();
1079
1080 // Some builtin types (such as Objective-C's "id", "sel", and
1081 // "Class") have associated declarations. Create cursors for those.
1082 QualType VisitType;
1083 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001084 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001085 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001086 case BuiltinType::Char_U:
1087 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001088 case BuiltinType::Char16:
1089 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001090 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001091 case BuiltinType::UInt:
1092 case BuiltinType::ULong:
1093 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001094 case BuiltinType::UInt128:
1095 case BuiltinType::Char_S:
1096 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001097 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001098 case BuiltinType::Short:
1099 case BuiltinType::Int:
1100 case BuiltinType::Long:
1101 case BuiltinType::LongLong:
1102 case BuiltinType::Int128:
1103 case BuiltinType::Float:
1104 case BuiltinType::Double:
1105 case BuiltinType::LongDouble:
1106 case BuiltinType::NullPtr:
1107 case BuiltinType::Overload:
1108 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001109 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001110
1111 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001112 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001113
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001114 case BuiltinType::ObjCId:
1115 VisitType = Context.getObjCIdType();
1116 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001117
1118 case BuiltinType::ObjCClass:
1119 VisitType = Context.getObjCClassType();
1120 break;
1121
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001122 case BuiltinType::ObjCSel:
1123 VisitType = Context.getObjCSelType();
1124 break;
1125 }
1126
1127 if (!VisitType.isNull()) {
1128 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001129 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001130 TU));
1131 }
1132
1133 return false;
1134}
1135
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001136bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1137 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1138}
1139
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001140bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1141 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1142}
1143
1144bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1145 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1146}
1147
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001148bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1149 // FIXME: We can't visit the template template parameter, but there's
1150 // no context information with which we can match up the depth/index in the
1151 // type to the appropriate
1152 return false;
1153}
1154
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001155bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1156 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1157 return true;
1158
John McCallc12c5bb2010-05-15 11:32:37 +00001159 return false;
1160}
1161
1162bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1163 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1164 return true;
1165
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001166 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1167 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1168 TU)))
1169 return true;
1170 }
1171
1172 return false;
1173}
1174
1175bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001176 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001177}
1178
1179bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1180 return Visit(TL.getPointeeLoc());
1181}
1182
1183bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1184 return Visit(TL.getPointeeLoc());
1185}
1186
1187bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1188 return Visit(TL.getPointeeLoc());
1189}
1190
1191bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001192 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001193}
1194
1195bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001196 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001197}
1198
Douglas Gregor01829d32010-08-31 14:41:23 +00001199bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1200 bool SkipResultType) {
1201 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001202 return true;
1203
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001204 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001205 if (Decl *D = TL.getArg(I))
1206 if (Visit(MakeCXCursor(D, TU)))
1207 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001208
1209 return false;
1210}
1211
1212bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1213 if (Visit(TL.getElementLoc()))
1214 return true;
1215
1216 if (Expr *Size = TL.getSizeExpr())
1217 return Visit(MakeCXCursor(Size, StmtParent, TU));
1218
1219 return false;
1220}
1221
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001222bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1223 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001224 // Visit the template name.
1225 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1226 TL.getTemplateNameLoc()))
1227 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001228
1229 // Visit the template arguments.
1230 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1231 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1232 return true;
1233
1234 return false;
1235}
1236
Douglas Gregor2332c112010-01-21 20:48:56 +00001237bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1238 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1239}
1240
1241bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1242 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1243 return Visit(TSInfo->getTypeLoc());
1244
1245 return false;
1246}
1247
Douglas Gregora59e3902010-01-21 23:27:09 +00001248bool CursorVisitor::VisitStmt(Stmt *S) {
1249 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1250 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001251 if (Stmt *C = *Child)
1252 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1253 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001254 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001255
Douglas Gregora59e3902010-01-21 23:27:09 +00001256 return false;
1257}
1258
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001259bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1260 // Specially handle CaseStmts because they can be nested, e.g.:
1261 //
1262 // case 1:
1263 // case 2:
1264 //
1265 // In this case the second CaseStmt is the child of the first. Walking
1266 // these recursively can blow out the stack.
1267 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1268 while (true) {
1269 // Set the Parent field to Cursor, then back to its old value once we're
1270 // done.
1271 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1272
1273 if (Stmt *LHS = S->getLHS())
1274 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1275 return true;
1276 if (Stmt *RHS = S->getRHS())
1277 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1278 return true;
1279 if (Stmt *SubStmt = S->getSubStmt()) {
1280 if (!isa<CaseStmt>(SubStmt))
1281 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1282
1283 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1284 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1285 Cursor = MakeCXCursor(CS, StmtParent, TU);
1286 if (RegionOfInterest.isValid()) {
1287 SourceRange Range = CS->getSourceRange();
1288 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1289 return false;
1290 }
1291
1292 switch (Visitor(Cursor, Parent, ClientData)) {
1293 case CXChildVisit_Break: return true;
1294 case CXChildVisit_Continue: return false;
1295 case CXChildVisit_Recurse:
1296 // Perform tail-recursion manually.
1297 S = CS;
1298 continue;
1299 }
1300 }
1301 return false;
1302 }
1303}
1304
Douglas Gregora59e3902010-01-21 23:27:09 +00001305bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1306 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1307 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001308 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001309 return true;
1310 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001311
Douglas Gregora59e3902010-01-21 23:27:09 +00001312 return false;
1313}
1314
Douglas Gregorf5bab412010-01-22 01:00:11 +00001315bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1316 if (VarDecl *Var = S->getConditionVariable()) {
1317 if (Visit(MakeCXCursor(Var, TU)))
1318 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001319 }
1320
Douglas Gregor263b47b2010-01-25 16:12:32 +00001321 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1322 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001323 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1324 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001325 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1326 return true;
1327
1328 return false;
1329}
1330
1331bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1332 if (VarDecl *Var = S->getConditionVariable()) {
1333 if (Visit(MakeCXCursor(Var, TU)))
1334 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001335 }
1336
Douglas Gregor263b47b2010-01-25 16:12:32 +00001337 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1338 return true;
1339 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1340 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001341
Douglas Gregor263b47b2010-01-25 16:12:32 +00001342 return false;
1343}
1344
1345bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1346 if (VarDecl *Var = S->getConditionVariable()) {
1347 if (Visit(MakeCXCursor(Var, TU)))
1348 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001349 }
1350
Douglas Gregor263b47b2010-01-25 16:12:32 +00001351 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1352 return true;
1353 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001354 return true;
1355
Douglas Gregor263b47b2010-01-25 16:12:32 +00001356 return false;
1357}
1358
1359bool CursorVisitor::VisitForStmt(ForStmt *S) {
1360 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1361 return true;
1362 if (VarDecl *Var = S->getConditionVariable()) {
1363 if (Visit(MakeCXCursor(Var, TU)))
1364 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001365 }
1366
Douglas Gregor263b47b2010-01-25 16:12:32 +00001367 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1368 return true;
1369 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1370 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001371 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1372 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001373
Douglas Gregorf5bab412010-01-22 01:00:11 +00001374 return false;
1375}
1376
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001377bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1378 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1379 return true;
1380
1381 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1382 return true;
1383
1384 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1385 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1386 return true;
1387
1388 return false;
1389}
1390
Ted Kremenek3064ef92010-08-27 21:34:58 +00001391bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1392 if (D->isDefinition()) {
1393 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1394 E = D->bases_end(); I != E; ++I) {
1395 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1396 return true;
1397 }
1398 }
1399
1400 return VisitTagDecl(D);
1401}
1402
1403
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001404bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1405 return Visit(B->getBlockDecl());
1406}
1407
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001408bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1409 // FIXME: Visit fields as well?
1410 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1411 return true;
1412
1413 return VisitExpr(E);
1414}
1415
Douglas Gregor336fd812010-01-23 00:40:08 +00001416bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1417 if (E->isArgumentType()) {
1418 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1419 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001420
Douglas Gregor336fd812010-01-23 00:40:08 +00001421 return false;
1422 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001423
Douglas Gregor336fd812010-01-23 00:40:08 +00001424 return VisitExpr(E);
1425}
1426
1427bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1428 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1429 if (Visit(TSInfo->getTypeLoc()))
1430 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001431
Douglas Gregor336fd812010-01-23 00:40:08 +00001432 return VisitCastExpr(E);
1433}
1434
1435bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1436 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1437 if (Visit(TSInfo->getTypeLoc()))
1438 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001439
Douglas Gregor336fd812010-01-23 00:40:08 +00001440 return VisitExpr(E);
1441}
1442
Douglas Gregor648220e2010-08-10 15:02:34 +00001443bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1444 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1445 Visit(E->getArgTInfo2()->getTypeLoc());
1446}
1447
1448bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1449 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1450 return true;
1451
1452 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1453}
1454
Douglas Gregorc2350e52010-03-08 16:40:19 +00001455bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001456 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1457 if (Visit(TSInfo->getTypeLoc()))
1458 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001459
1460 return VisitExpr(E);
1461}
1462
Douglas Gregor81d34662010-04-20 15:39:42 +00001463bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1464 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1465}
1466
1467
Ted Kremenek09dfa372010-02-18 05:46:33 +00001468bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001469 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1470 i != e; ++i)
1471 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001472 return true;
1473
1474 return false;
1475}
1476
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001477extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001478CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1479 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001480 // We use crash recovery to make some of our APIs more reliable, implicitly
1481 // enable it.
1482 llvm::CrashRecoveryContext::Enable();
1483
Douglas Gregora030b7c2010-01-22 20:35:53 +00001484 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001485 if (excludeDeclarationsFromPCH)
1486 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001487 if (displayDiagnostics)
1488 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001489 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001490}
1491
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001492void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001493 if (CIdx)
1494 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001495 if (getenv("LIBCLANG_TIMING"))
1496 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001497}
1498
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001499void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001500 if (CIdx) {
1501 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1502 CXXIdx->setUseExternalASTGeneration(value);
1503 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001504}
1505
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001506CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001507 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001508 if (!CIdx)
1509 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001510
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001511 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001512
Douglas Gregor28019772010-04-05 23:52:57 +00001513 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001514 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001515 CXXIdx->getOnlyLocalDecls(),
1516 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001517}
1518
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001519unsigned clang_defaultEditingTranslationUnitOptions() {
1520 return CXTranslationUnit_PrecompiledPreamble;
1521}
1522
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001523CXTranslationUnit
1524clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1525 const char *source_filename,
1526 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001527 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001528 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001529 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001530 return clang_parseTranslationUnit(CIdx, source_filename,
1531 command_line_args, num_command_line_args,
1532 unsaved_files, num_unsaved_files,
1533 CXTranslationUnit_DetailedPreprocessingRecord);
1534}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001535
1536struct ParseTranslationUnitInfo {
1537 CXIndex CIdx;
1538 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001539 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001540 int num_command_line_args;
1541 struct CXUnsavedFile *unsaved_files;
1542 unsigned num_unsaved_files;
1543 unsigned options;
1544 CXTranslationUnit result;
1545};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001546static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001547 ParseTranslationUnitInfo *PTUI =
1548 static_cast<ParseTranslationUnitInfo*>(UserData);
1549 CXIndex CIdx = PTUI->CIdx;
1550 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001551 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001552 int num_command_line_args = PTUI->num_command_line_args;
1553 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1554 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1555 unsigned options = PTUI->options;
1556 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001557
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001558 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001559 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001560
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001561 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1562
Douglas Gregor44c181a2010-07-23 00:33:23 +00001563 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001564 bool CompleteTranslationUnit
1565 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001566 bool CacheCodeCompetionResults
1567 = options & CXTranslationUnit_CacheCompletionResults;
1568
Douglas Gregor5352ac02010-01-28 00:27:43 +00001569 // Configure the diagnostics.
1570 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001571 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1572 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001573
Douglas Gregor4db64a42010-01-23 00:14:00 +00001574 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1575 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001576 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001577 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001578 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001579 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1580 Buffer));
1581 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001582
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001583 if (!CXXIdx->getUseExternalASTGeneration()) {
1584 llvm::SmallVector<const char *, 16> Args;
1585
1586 // The 'source_filename' argument is optional. If the caller does not
1587 // specify it then it is assumed that the source file is specified
1588 // in the actual argument list.
1589 if (source_filename)
1590 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001591
1592 // Since the Clang C library is primarily used by batch tools dealing with
1593 // (often very broken) source code, where spell-checking can have a
1594 // significant negative impact on performance (particularly when
1595 // precompiled headers are involved), we disable it by default.
1596 // Note that we place this argument early in the list, so that it can be
1597 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001598 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001599
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001600 Args.insert(Args.end(), command_line_args,
1601 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001602
Douglas Gregor44c181a2010-07-23 00:33:23 +00001603 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001604 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1605 Args.push_back("-Xclang");
1606 Args.push_back("-detailed-preprocessing-record");
1607 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001608
Douglas Gregor5352ac02010-01-28 00:27:43 +00001609 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001610
Ted Kremenek29b72842010-01-07 22:49:05 +00001611#ifdef USE_CRASHTRACER
1612 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001613#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001614
Daniel Dunbar94220972009-12-05 02:17:18 +00001615 llvm::OwningPtr<ASTUnit> Unit(
1616 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001617 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001618 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001619 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001620 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001621 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001622 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001623 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001624 CompleteTranslationUnit,
1625 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001626
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001627 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001628 // Make sure to check that 'Unit' is non-NULL.
1629 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001630 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1631 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001632 D != DEnd; ++D) {
1633 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001634 CXString Msg = clang_formatDiagnostic(&Diag,
1635 clang_defaultDiagnosticDisplayOptions());
1636 fprintf(stderr, "%s\n", clang_getCString(Msg));
1637 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001638 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001639#ifdef LLVM_ON_WIN32
1640 // On Windows, force a flush, since there may be multiple copies of
1641 // stderr and stdout in the file system, all with different buffers
1642 // but writing to the same device.
1643 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001644#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001645 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001646 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001647
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001648 PTUI->result = Unit.take();
1649 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001650 }
1651
Ted Kremenek139ba862009-10-22 00:03:57 +00001652 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001653 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001654
Ted Kremenek139ba862009-10-22 00:03:57 +00001655 // First add the complete path to the 'clang' executable.
1656 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001657 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001658
Ted Kremenek139ba862009-10-22 00:03:57 +00001659 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001660 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001661
Ted Kremenek139ba862009-10-22 00:03:57 +00001662 // The 'source_filename' argument is optional. If the caller does not
1663 // specify it then it is assumed that the source file is specified
1664 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001665 if (source_filename)
1666 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001667
Steve Naroff37b5ac22009-10-15 20:50:09 +00001668 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001669 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001670 char astTmpFile[L_tmpnam];
1671 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001672
1673 // Since the Clang C library is primarily used by batch tools dealing with
1674 // (often very broken) source code, where spell-checking can have a
1675 // significant negative impact on performance (particularly when
1676 // precompiled headers are involved), we disable it by default.
1677 // Note that we place this argument early in the list, so that it can be
1678 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001679 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001680
Douglas Gregor4db64a42010-01-23 00:14:00 +00001681 // Remap any unsaved files to temporary files.
1682 std::vector<llvm::sys::Path> TemporaryFiles;
1683 std::vector<std::string> RemapArgs;
1684 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001685 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001686
Douglas Gregor4db64a42010-01-23 00:14:00 +00001687 // The pointers into the elements of RemapArgs are stable because we
1688 // won't be adding anything to RemapArgs after this point.
1689 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1690 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001691
Ted Kremenek139ba862009-10-22 00:03:57 +00001692 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1693 for (int i = 0; i < num_command_line_args; ++i)
1694 if (const char *arg = command_line_args[i]) {
1695 if (strcmp(arg, "-o") == 0) {
1696 ++i; // Also skip the matching argument.
1697 continue;
1698 }
1699 if (strcmp(arg, "-emit-ast") == 0 ||
1700 strcmp(arg, "-c") == 0 ||
1701 strcmp(arg, "-fsyntax-only") == 0) {
1702 continue;
1703 }
1704
1705 // Keep the argument.
1706 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001707 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001708
Douglas Gregord93256e2010-01-28 06:00:51 +00001709 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001710 char tmpFileResults[L_tmpnam];
1711 char *tmpResultsFileName = tmpnam(tmpFileResults);
1712 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001713 TemporaryFiles.push_back(DiagnosticsFile);
1714 argv.push_back("-fdiagnostics-binary");
1715
Douglas Gregor44c181a2010-07-23 00:33:23 +00001716 // Do we need the detailed preprocessing record?
1717 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1718 argv.push_back("-Xclang");
1719 argv.push_back("-detailed-preprocessing-record");
1720 }
1721
Ted Kremenek139ba862009-10-22 00:03:57 +00001722 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001723 argv.push_back(NULL);
1724
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001725 // Invoke 'clang'.
1726 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1727 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001728 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001729 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1730 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001731 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001732 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001733 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001734
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001735 if (!ErrMsg.empty()) {
1736 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001737 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001738 I != E; ++I) {
1739 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001740 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001741 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001742 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001743
Daniel Dunbar32141c82010-02-23 20:23:45 +00001744 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001745 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001746
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001747 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001748 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001749 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001750 RemappedFiles.size(),
1751 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001752 if (ATU) {
1753 LoadSerializedDiagnostics(DiagnosticsFile,
1754 num_unsaved_files, unsaved_files,
1755 ATU->getFileManager(),
1756 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001757 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001758 } else if (CXXIdx->getDisplayDiagnostics()) {
1759 // We failed to load the ASTUnit, but we can still deserialize the
1760 // diagnostics and emit them.
1761 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001762 Diagnostic Diag;
1763 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001764 // FIXME: Faked LangOpts!
1765 LangOptions LangOpts;
1766 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1767 LoadSerializedDiagnostics(DiagnosticsFile,
1768 num_unsaved_files, unsaved_files,
1769 FileMgr, SourceMgr, Diags);
1770 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1771 DEnd = Diags.end();
1772 D != DEnd; ++D) {
1773 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001774 CXString Msg = clang_formatDiagnostic(&Diag,
1775 clang_defaultDiagnosticDisplayOptions());
1776 fprintf(stderr, "%s\n", clang_getCString(Msg));
1777 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001778 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001779
1780#ifdef LLVM_ON_WIN32
1781 // On Windows, force a flush, since there may be multiple copies of
1782 // stderr and stdout in the file system, all with different buffers
1783 // but writing to the same device.
1784 fflush(stderr);
1785#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001786 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001787
Douglas Gregor313e26c2010-02-18 23:35:40 +00001788 if (ATU) {
1789 // Make the translation unit responsible for destroying all temporary files.
1790 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1791 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001792 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001793 } else {
1794 // Destroy all of the temporary files now; they can't be referenced any
1795 // longer.
1796 llvm::sys::Path(astTmpFile).eraseFromDisk();
1797 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1798 TemporaryFiles[i].eraseFromDisk();
1799 }
1800
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001801 PTUI->result = ATU;
1802}
1803CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1804 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001805 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001806 int num_command_line_args,
1807 struct CXUnsavedFile *unsaved_files,
1808 unsigned num_unsaved_files,
1809 unsigned options) {
1810 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1811 num_command_line_args, unsaved_files, num_unsaved_files,
1812 options, 0 };
1813 llvm::CrashRecoveryContext CRC;
1814
1815 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001816 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1817 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1818 fprintf(stderr, " 'command_line_args' : [");
1819 for (int i = 0; i != num_command_line_args; ++i) {
1820 if (i)
1821 fprintf(stderr, ", ");
1822 fprintf(stderr, "'%s'", command_line_args[i]);
1823 }
1824 fprintf(stderr, "],\n");
1825 fprintf(stderr, " 'unsaved_files' : [");
1826 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1827 if (i)
1828 fprintf(stderr, ", ");
1829 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1830 unsaved_files[i].Length);
1831 }
1832 fprintf(stderr, "],\n");
1833 fprintf(stderr, " 'options' : %d,\n", options);
1834 fprintf(stderr, "}\n");
1835
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001836 return 0;
1837 }
1838
1839 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001840}
1841
Douglas Gregor19998442010-08-13 15:35:05 +00001842unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1843 return CXSaveTranslationUnit_None;
1844}
1845
1846int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1847 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001848 if (!TU)
1849 return 1;
1850
1851 return static_cast<ASTUnit *>(TU)->Save(FileName);
1852}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001853
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001854void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001855 if (CTUnit) {
1856 // If the translation unit has been marked as unsafe to free, just discard
1857 // it.
1858 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1859 return;
1860
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001861 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001862 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001863}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001864
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001865unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1866 return CXReparse_None;
1867}
1868
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001869struct ReparseTranslationUnitInfo {
1870 CXTranslationUnit TU;
1871 unsigned num_unsaved_files;
1872 struct CXUnsavedFile *unsaved_files;
1873 unsigned options;
1874 int result;
1875};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001876static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001877 ReparseTranslationUnitInfo *RTUI =
1878 static_cast<ReparseTranslationUnitInfo*>(UserData);
1879 CXTranslationUnit TU = RTUI->TU;
1880 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1881 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1882 unsigned options = RTUI->options;
1883 (void) options;
1884 RTUI->result = 1;
1885
Douglas Gregorabc563f2010-07-19 21:46:24 +00001886 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001887 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001888
1889 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1890 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1891 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1892 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001893 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001894 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1895 Buffer));
1896 }
1897
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001898 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1899 RemappedFiles.size()))
1900 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001901}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001902int clang_reparseTranslationUnit(CXTranslationUnit TU,
1903 unsigned num_unsaved_files,
1904 struct CXUnsavedFile *unsaved_files,
1905 unsigned options) {
1906 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1907 options, 0 };
1908 llvm::CrashRecoveryContext CRC;
1909
1910 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001911 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001912 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1913 return 1;
1914 }
1915
1916 return RTUI.result;
1917}
1918
Douglas Gregordf95a132010-08-09 20:45:32 +00001919
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001920CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001921 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001922 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001923
Steve Naroff77accc12009-09-03 18:19:54 +00001924 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001925 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001926}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001927
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001928CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001929 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001930 return Result;
1931}
1932
Ted Kremenekfb480492010-01-13 21:46:36 +00001933} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001934
Ted Kremenekfb480492010-01-13 21:46:36 +00001935//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001936// CXSourceLocation and CXSourceRange Operations.
1937//===----------------------------------------------------------------------===//
1938
Douglas Gregorb9790342010-01-22 21:44:22 +00001939extern "C" {
1940CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001941 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001942 return Result;
1943}
1944
1945unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001946 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1947 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1948 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001949}
1950
1951CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1952 CXFile file,
1953 unsigned line,
1954 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001955 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001956 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001957
Douglas Gregorb9790342010-01-22 21:44:22 +00001958 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1959 SourceLocation SLoc
1960 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001961 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001962 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001963
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001964 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001965}
1966
Douglas Gregor5352ac02010-01-28 00:27:43 +00001967CXSourceRange clang_getNullRange() {
1968 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1969 return Result;
1970}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001971
Douglas Gregor5352ac02010-01-28 00:27:43 +00001972CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1973 if (begin.ptr_data[0] != end.ptr_data[0] ||
1974 begin.ptr_data[1] != end.ptr_data[1])
1975 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001976
1977 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001978 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001979 return Result;
1980}
1981
Douglas Gregor46766dc2010-01-26 19:19:08 +00001982void clang_getInstantiationLocation(CXSourceLocation location,
1983 CXFile *file,
1984 unsigned *line,
1985 unsigned *column,
1986 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001987 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1988
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001989 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001990 if (file)
1991 *file = 0;
1992 if (line)
1993 *line = 0;
1994 if (column)
1995 *column = 0;
1996 if (offset)
1997 *offset = 0;
1998 return;
1999 }
2000
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002001 const SourceManager &SM =
2002 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002003 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002004
2005 if (file)
2006 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2007 if (line)
2008 *line = SM.getInstantiationLineNumber(InstLoc);
2009 if (column)
2010 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002011 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002012 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002013}
2014
Douglas Gregor1db19de2010-01-19 21:36:55 +00002015CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002016 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002017 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002018 return Result;
2019}
2020
2021CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002022 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002023 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002024 return Result;
2025}
2026
Douglas Gregorb9790342010-01-22 21:44:22 +00002027} // end: extern "C"
2028
Douglas Gregor1db19de2010-01-19 21:36:55 +00002029//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002030// CXFile Operations.
2031//===----------------------------------------------------------------------===//
2032
2033extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002034CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002035 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002036 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002037
Steve Naroff88145032009-10-27 14:35:18 +00002038 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002039 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002040}
2041
2042time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002043 if (!SFile)
2044 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002045
Steve Naroff88145032009-10-27 14:35:18 +00002046 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2047 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002048}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002049
Douglas Gregorb9790342010-01-22 21:44:22 +00002050CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2051 if (!tu)
2052 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002053
Douglas Gregorb9790342010-01-22 21:44:22 +00002054 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002055
Douglas Gregorb9790342010-01-22 21:44:22 +00002056 FileManager &FMgr = CXXUnit->getFileManager();
2057 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2058 return const_cast<FileEntry *>(File);
2059}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002060
Ted Kremenekfb480492010-01-13 21:46:36 +00002061} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002062
Ted Kremenekfb480492010-01-13 21:46:36 +00002063//===----------------------------------------------------------------------===//
2064// CXCursor Operations.
2065//===----------------------------------------------------------------------===//
2066
Ted Kremenekfb480492010-01-13 21:46:36 +00002067static Decl *getDeclFromExpr(Stmt *E) {
2068 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2069 return RefExpr->getDecl();
2070 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2071 return ME->getMemberDecl();
2072 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2073 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002074
Ted Kremenekfb480492010-01-13 21:46:36 +00002075 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2076 return getDeclFromExpr(CE->getCallee());
2077 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2078 return getDeclFromExpr(CE->getSubExpr());
2079 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2080 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002081
Ted Kremenekfb480492010-01-13 21:46:36 +00002082 return 0;
2083}
2084
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002085static SourceLocation getLocationFromExpr(Expr *E) {
2086 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2087 return /*FIXME:*/Msg->getLeftLoc();
2088 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2089 return DRE->getLocation();
2090 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2091 return Member->getMemberLoc();
2092 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2093 return Ivar->getLocation();
2094 return E->getLocStart();
2095}
2096
Ted Kremenekfb480492010-01-13 21:46:36 +00002097extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002098
2099unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002100 CXCursorVisitor visitor,
2101 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002102 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002103
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002104 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2105 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002106 return CursorVis.VisitChildren(parent);
2107}
2108
Douglas Gregor78205d42010-01-20 21:45:58 +00002109static CXString getDeclSpelling(Decl *D) {
2110 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2111 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002112 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002113
Douglas Gregor78205d42010-01-20 21:45:58 +00002114 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002115 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002116
Douglas Gregor78205d42010-01-20 21:45:58 +00002117 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2118 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2119 // and returns different names. NamedDecl returns the class name and
2120 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002121 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002122
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002123 if (isa<UsingDirectiveDecl>(D))
2124 return createCXString("");
2125
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002126 llvm::SmallString<1024> S;
2127 llvm::raw_svector_ostream os(S);
2128 ND->printName(os);
2129
2130 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002131}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002132
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002133CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002134 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002135 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002136
Steve Narofff334b4e2009-09-02 18:26:48 +00002137 if (clang_isReference(C.kind)) {
2138 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002139 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002140 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002141 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002142 }
2143 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002144 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002145 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002146 }
2147 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002148 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002149 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002150 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002151 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002152 case CXCursor_CXXBaseSpecifier: {
2153 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2154 return createCXString(B->getType().getAsString());
2155 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002156 case CXCursor_TypeRef: {
2157 TypeDecl *Type = getCursorTypeRef(C).first;
2158 assert(Type && "Missing type decl");
2159
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002160 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2161 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002162 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002163 case CXCursor_TemplateRef: {
2164 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002165 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002166
2167 return createCXString(Template->getNameAsString());
2168 }
Douglas Gregor69319002010-08-31 23:48:11 +00002169
2170 case CXCursor_NamespaceRef: {
2171 NamedDecl *NS = getCursorNamespaceRef(C).first;
2172 assert(NS && "Missing namespace decl");
2173
2174 return createCXString(NS->getNameAsString());
2175 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002176
Daniel Dunbaracca7252009-11-30 20:42:49 +00002177 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002178 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002179 }
2180 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002181
2182 if (clang_isExpression(C.kind)) {
2183 Decl *D = getDeclFromExpr(getCursorExpr(C));
2184 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002185 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002186 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002187 }
2188
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002189 if (C.kind == CXCursor_MacroInstantiation)
2190 return createCXString(getCursorMacroInstantiation(C)->getName()
2191 ->getNameStart());
2192
Douglas Gregor572feb22010-03-18 18:04:21 +00002193 if (C.kind == CXCursor_MacroDefinition)
2194 return createCXString(getCursorMacroDefinition(C)->getName()
2195 ->getNameStart());
2196
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002197 if (clang_isDeclaration(C.kind))
2198 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002199
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002200 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002201}
2202
Ted Kremeneke68fff62010-02-17 00:41:32 +00002203CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002204 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002205 case CXCursor_FunctionDecl:
2206 return createCXString("FunctionDecl");
2207 case CXCursor_TypedefDecl:
2208 return createCXString("TypedefDecl");
2209 case CXCursor_EnumDecl:
2210 return createCXString("EnumDecl");
2211 case CXCursor_EnumConstantDecl:
2212 return createCXString("EnumConstantDecl");
2213 case CXCursor_StructDecl:
2214 return createCXString("StructDecl");
2215 case CXCursor_UnionDecl:
2216 return createCXString("UnionDecl");
2217 case CXCursor_ClassDecl:
2218 return createCXString("ClassDecl");
2219 case CXCursor_FieldDecl:
2220 return createCXString("FieldDecl");
2221 case CXCursor_VarDecl:
2222 return createCXString("VarDecl");
2223 case CXCursor_ParmDecl:
2224 return createCXString("ParmDecl");
2225 case CXCursor_ObjCInterfaceDecl:
2226 return createCXString("ObjCInterfaceDecl");
2227 case CXCursor_ObjCCategoryDecl:
2228 return createCXString("ObjCCategoryDecl");
2229 case CXCursor_ObjCProtocolDecl:
2230 return createCXString("ObjCProtocolDecl");
2231 case CXCursor_ObjCPropertyDecl:
2232 return createCXString("ObjCPropertyDecl");
2233 case CXCursor_ObjCIvarDecl:
2234 return createCXString("ObjCIvarDecl");
2235 case CXCursor_ObjCInstanceMethodDecl:
2236 return createCXString("ObjCInstanceMethodDecl");
2237 case CXCursor_ObjCClassMethodDecl:
2238 return createCXString("ObjCClassMethodDecl");
2239 case CXCursor_ObjCImplementationDecl:
2240 return createCXString("ObjCImplementationDecl");
2241 case CXCursor_ObjCCategoryImplDecl:
2242 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002243 case CXCursor_CXXMethod:
2244 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002245 case CXCursor_UnexposedDecl:
2246 return createCXString("UnexposedDecl");
2247 case CXCursor_ObjCSuperClassRef:
2248 return createCXString("ObjCSuperClassRef");
2249 case CXCursor_ObjCProtocolRef:
2250 return createCXString("ObjCProtocolRef");
2251 case CXCursor_ObjCClassRef:
2252 return createCXString("ObjCClassRef");
2253 case CXCursor_TypeRef:
2254 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002255 case CXCursor_TemplateRef:
2256 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002257 case CXCursor_NamespaceRef:
2258 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002259 case CXCursor_UnexposedExpr:
2260 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002261 case CXCursor_BlockExpr:
2262 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002263 case CXCursor_DeclRefExpr:
2264 return createCXString("DeclRefExpr");
2265 case CXCursor_MemberRefExpr:
2266 return createCXString("MemberRefExpr");
2267 case CXCursor_CallExpr:
2268 return createCXString("CallExpr");
2269 case CXCursor_ObjCMessageExpr:
2270 return createCXString("ObjCMessageExpr");
2271 case CXCursor_UnexposedStmt:
2272 return createCXString("UnexposedStmt");
2273 case CXCursor_InvalidFile:
2274 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002275 case CXCursor_InvalidCode:
2276 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002277 case CXCursor_NoDeclFound:
2278 return createCXString("NoDeclFound");
2279 case CXCursor_NotImplemented:
2280 return createCXString("NotImplemented");
2281 case CXCursor_TranslationUnit:
2282 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002283 case CXCursor_UnexposedAttr:
2284 return createCXString("UnexposedAttr");
2285 case CXCursor_IBActionAttr:
2286 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002287 case CXCursor_IBOutletAttr:
2288 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002289 case CXCursor_IBOutletCollectionAttr:
2290 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002291 case CXCursor_PreprocessingDirective:
2292 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002293 case CXCursor_MacroDefinition:
2294 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002295 case CXCursor_MacroInstantiation:
2296 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002297 case CXCursor_Namespace:
2298 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002299 case CXCursor_LinkageSpec:
2300 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002301 case CXCursor_CXXBaseSpecifier:
2302 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002303 case CXCursor_Constructor:
2304 return createCXString("CXXConstructor");
2305 case CXCursor_Destructor:
2306 return createCXString("CXXDestructor");
2307 case CXCursor_ConversionFunction:
2308 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002309 case CXCursor_TemplateTypeParameter:
2310 return createCXString("TemplateTypeParameter");
2311 case CXCursor_NonTypeTemplateParameter:
2312 return createCXString("NonTypeTemplateParameter");
2313 case CXCursor_TemplateTemplateParameter:
2314 return createCXString("TemplateTemplateParameter");
2315 case CXCursor_FunctionTemplate:
2316 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002317 case CXCursor_ClassTemplate:
2318 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002319 case CXCursor_ClassTemplatePartialSpecialization:
2320 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002321 case CXCursor_NamespaceAlias:
2322 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002323 case CXCursor_UsingDirective:
2324 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002325 case CXCursor_UsingDeclaration:
2326 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002327 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002328
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002329 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002330 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002331}
Steve Naroff89922f82009-08-31 00:59:03 +00002332
Ted Kremeneke68fff62010-02-17 00:41:32 +00002333enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2334 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002335 CXClientData client_data) {
2336 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2337 *BestCursor = cursor;
2338 return CXChildVisit_Recurse;
2339}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002340
Douglas Gregorb9790342010-01-22 21:44:22 +00002341CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2342 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002343 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002344
Douglas Gregorb9790342010-01-22 21:44:22 +00002345 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002346 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2347
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002348 // Translate the given source location to make it point at the beginning of
2349 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002350 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002351
2352 // Guard against an invalid SourceLocation, or we may assert in one
2353 // of the following calls.
2354 if (SLoc.isInvalid())
2355 return clang_getNullCursor();
2356
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002357 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2358 CXXUnit->getASTContext().getLangOptions());
2359
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002360 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2361 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002362 // FIXME: Would be great to have a "hint" cursor, then walk from that
2363 // hint cursor upward until we find a cursor whose source range encloses
2364 // the region of interest, rather than starting from the translation unit.
2365 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002366 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002367 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002368 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002369 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002370 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002371}
2372
Ted Kremenek73885552009-11-17 19:28:59 +00002373CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002374 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002375}
2376
2377unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002378 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002379}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002380
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002381unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002382 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2383}
2384
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002385unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002386 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2387}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002388
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002389unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002390 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2391}
2392
Douglas Gregor97b98722010-01-19 23:20:36 +00002393unsigned clang_isExpression(enum CXCursorKind K) {
2394 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2395}
2396
2397unsigned clang_isStatement(enum CXCursorKind K) {
2398 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2399}
2400
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002401unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2402 return K == CXCursor_TranslationUnit;
2403}
2404
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002405unsigned clang_isPreprocessing(enum CXCursorKind K) {
2406 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2407}
2408
Ted Kremenekad6eff62010-03-08 21:17:29 +00002409unsigned clang_isUnexposed(enum CXCursorKind K) {
2410 switch (K) {
2411 case CXCursor_UnexposedDecl:
2412 case CXCursor_UnexposedExpr:
2413 case CXCursor_UnexposedStmt:
2414 case CXCursor_UnexposedAttr:
2415 return true;
2416 default:
2417 return false;
2418 }
2419}
2420
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002421CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002422 return C.kind;
2423}
2424
Douglas Gregor98258af2010-01-18 22:46:11 +00002425CXSourceLocation clang_getCursorLocation(CXCursor C) {
2426 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002427 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002428 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002429 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2430 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002431 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002432 }
2433
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002434 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002435 std::pair<ObjCProtocolDecl *, SourceLocation> P
2436 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002437 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002438 }
2439
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002440 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002441 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2442 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002443 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002444 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002445
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002446 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002447 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002448 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002449 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002450
2451 case CXCursor_TemplateRef: {
2452 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2453 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2454 }
2455
Douglas Gregor69319002010-08-31 23:48:11 +00002456 case CXCursor_NamespaceRef: {
2457 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2458 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2459 }
2460
Ted Kremenek3064ef92010-08-27 21:34:58 +00002461 case CXCursor_CXXBaseSpecifier: {
2462 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2463 return clang_getNullLocation();
2464 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002465
Douglas Gregorf46034a2010-01-18 23:41:10 +00002466 default:
2467 // FIXME: Need a way to enumerate all non-reference cases.
2468 llvm_unreachable("Missed a reference kind");
2469 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002470 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002471
2472 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002473 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002474 getLocationFromExpr(getCursorExpr(C)));
2475
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002476 if (C.kind == CXCursor_PreprocessingDirective) {
2477 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2478 return cxloc::translateSourceLocation(getCursorContext(C), L);
2479 }
Douglas Gregor48072312010-03-18 15:23:44 +00002480
2481 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002482 SourceLocation L
2483 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002484 return cxloc::translateSourceLocation(getCursorContext(C), L);
2485 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002486
2487 if (C.kind == CXCursor_MacroDefinition) {
2488 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2489 return cxloc::translateSourceLocation(getCursorContext(C), L);
2490 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002491
Ted Kremenek9a700d22010-05-12 06:16:13 +00002492 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002493 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002494
Douglas Gregorf46034a2010-01-18 23:41:10 +00002495 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002496 SourceLocation Loc = D->getLocation();
2497 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2498 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002499 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002500}
Douglas Gregora7bde202010-01-19 00:34:46 +00002501
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002502} // end extern "C"
2503
2504static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002505 if (clang_isReference(C.kind)) {
2506 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002507 case CXCursor_ObjCSuperClassRef:
2508 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002509
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002510 case CXCursor_ObjCProtocolRef:
2511 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002512
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002513 case CXCursor_ObjCClassRef:
2514 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002515
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002516 case CXCursor_TypeRef:
2517 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002518
2519 case CXCursor_TemplateRef:
2520 return getCursorTemplateRef(C).second;
2521
Douglas Gregor69319002010-08-31 23:48:11 +00002522 case CXCursor_NamespaceRef:
2523 return getCursorNamespaceRef(C).second;
2524
Ted Kremenek3064ef92010-08-27 21:34:58 +00002525 case CXCursor_CXXBaseSpecifier:
2526 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2527 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002528
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002529 default:
2530 // FIXME: Need a way to enumerate all non-reference cases.
2531 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002532 }
2533 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002534
2535 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002536 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002537
2538 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002539 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002540
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002541 if (C.kind == CXCursor_PreprocessingDirective)
2542 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002543
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002544 if (C.kind == CXCursor_MacroInstantiation)
2545 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002546
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002547 if (C.kind == CXCursor_MacroDefinition)
2548 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002549
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002550 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2551 return getCursorDecl(C)->getSourceRange();
2552
2553 return SourceRange();
2554}
2555
2556extern "C" {
2557
2558CXSourceRange clang_getCursorExtent(CXCursor C) {
2559 SourceRange R = getRawCursorExtent(C);
2560 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002561 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002562
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002563 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002564}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002565
2566CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002567 if (clang_isInvalid(C.kind))
2568 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002569
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002570 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002571 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002572 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002573
Douglas Gregor97b98722010-01-19 23:20:36 +00002574 if (clang_isExpression(C.kind)) {
2575 Decl *D = getDeclFromExpr(getCursorExpr(C));
2576 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002577 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002578 return clang_getNullCursor();
2579 }
2580
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002581 if (C.kind == CXCursor_MacroInstantiation) {
2582 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2583 return MakeMacroDefinitionCursor(Def, CXXUnit);
2584 }
2585
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002586 if (!clang_isReference(C.kind))
2587 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002588
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002589 switch (C.kind) {
2590 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002591 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002592
2593 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002594 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002595
2596 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002597 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002598
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002599 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002600 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002601
2602 case CXCursor_TemplateRef:
2603 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2604
Douglas Gregor69319002010-08-31 23:48:11 +00002605 case CXCursor_NamespaceRef:
2606 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2607
Ted Kremenek3064ef92010-08-27 21:34:58 +00002608 case CXCursor_CXXBaseSpecifier: {
2609 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2610 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2611 CXXUnit));
2612 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002613
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002614 default:
2615 // We would prefer to enumerate all non-reference cursor kinds here.
2616 llvm_unreachable("Unhandled reference cursor kind");
2617 break;
2618 }
2619 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002620
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002621 return clang_getNullCursor();
2622}
2623
Douglas Gregorb6998662010-01-19 19:34:47 +00002624CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002625 if (clang_isInvalid(C.kind))
2626 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002627
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002628 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002629
Douglas Gregorb6998662010-01-19 19:34:47 +00002630 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002631 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002632 C = clang_getCursorReferenced(C);
2633 WasReference = true;
2634 }
2635
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002636 if (C.kind == CXCursor_MacroInstantiation)
2637 return clang_getCursorReferenced(C);
2638
Douglas Gregorb6998662010-01-19 19:34:47 +00002639 if (!clang_isDeclaration(C.kind))
2640 return clang_getNullCursor();
2641
2642 Decl *D = getCursorDecl(C);
2643 if (!D)
2644 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002645
Douglas Gregorb6998662010-01-19 19:34:47 +00002646 switch (D->getKind()) {
2647 // Declaration kinds that don't really separate the notions of
2648 // declaration and definition.
2649 case Decl::Namespace:
2650 case Decl::Typedef:
2651 case Decl::TemplateTypeParm:
2652 case Decl::EnumConstant:
2653 case Decl::Field:
2654 case Decl::ObjCIvar:
2655 case Decl::ObjCAtDefsField:
2656 case Decl::ImplicitParam:
2657 case Decl::ParmVar:
2658 case Decl::NonTypeTemplateParm:
2659 case Decl::TemplateTemplateParm:
2660 case Decl::ObjCCategoryImpl:
2661 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002662 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002663 case Decl::LinkageSpec:
2664 case Decl::ObjCPropertyImpl:
2665 case Decl::FileScopeAsm:
2666 case Decl::StaticAssert:
2667 case Decl::Block:
2668 return C;
2669
2670 // Declaration kinds that don't make any sense here, but are
2671 // nonetheless harmless.
2672 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002673 break;
2674
2675 // Declaration kinds for which the definition is not resolvable.
2676 case Decl::UnresolvedUsingTypename:
2677 case Decl::UnresolvedUsingValue:
2678 break;
2679
2680 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002681 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2682 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002683
2684 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002685 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002686
2687 case Decl::Enum:
2688 case Decl::Record:
2689 case Decl::CXXRecord:
2690 case Decl::ClassTemplateSpecialization:
2691 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002692 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002693 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002694 return clang_getNullCursor();
2695
2696 case Decl::Function:
2697 case Decl::CXXMethod:
2698 case Decl::CXXConstructor:
2699 case Decl::CXXDestructor:
2700 case Decl::CXXConversion: {
2701 const FunctionDecl *Def = 0;
2702 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002703 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002704 return clang_getNullCursor();
2705 }
2706
2707 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002708 // Ask the variable if it has a definition.
2709 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2710 return MakeCXCursor(Def, CXXUnit);
2711 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002712 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002713
Douglas Gregorb6998662010-01-19 19:34:47 +00002714 case Decl::FunctionTemplate: {
2715 const FunctionDecl *Def = 0;
2716 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002717 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002718 return clang_getNullCursor();
2719 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002720
Douglas Gregorb6998662010-01-19 19:34:47 +00002721 case Decl::ClassTemplate: {
2722 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002723 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002724 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002725 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002726 return clang_getNullCursor();
2727 }
2728
2729 case Decl::Using: {
2730 UsingDecl *Using = cast<UsingDecl>(D);
2731 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002732 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2733 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002734 S != SEnd; ++S) {
2735 if (Def != clang_getNullCursor()) {
2736 // FIXME: We have no way to return multiple results.
2737 return clang_getNullCursor();
2738 }
2739
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002740 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002741 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002742 }
2743
2744 return Def;
2745 }
2746
2747 case Decl::UsingShadow:
2748 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002749 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002750 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002751
2752 case Decl::ObjCMethod: {
2753 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2754 if (Method->isThisDeclarationADefinition())
2755 return C;
2756
2757 // Dig out the method definition in the associated
2758 // @implementation, if we have it.
2759 // FIXME: The ASTs should make finding the definition easier.
2760 if (ObjCInterfaceDecl *Class
2761 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2762 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2763 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2764 Method->isInstanceMethod()))
2765 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002766 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002767
2768 return clang_getNullCursor();
2769 }
2770
2771 case Decl::ObjCCategory:
2772 if (ObjCCategoryImplDecl *Impl
2773 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002774 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002775 return clang_getNullCursor();
2776
2777 case Decl::ObjCProtocol:
2778 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2779 return C;
2780 return clang_getNullCursor();
2781
2782 case Decl::ObjCInterface:
2783 // There are two notions of a "definition" for an Objective-C
2784 // class: the interface and its implementation. When we resolved a
2785 // reference to an Objective-C class, produce the @interface as
2786 // the definition; when we were provided with the interface,
2787 // produce the @implementation as the definition.
2788 if (WasReference) {
2789 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2790 return C;
2791 } else if (ObjCImplementationDecl *Impl
2792 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002793 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002794 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002795
Douglas Gregorb6998662010-01-19 19:34:47 +00002796 case Decl::ObjCProperty:
2797 // FIXME: We don't really know where to find the
2798 // ObjCPropertyImplDecls that implement this property.
2799 return clang_getNullCursor();
2800
2801 case Decl::ObjCCompatibleAlias:
2802 if (ObjCInterfaceDecl *Class
2803 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2804 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002805 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002806
Douglas Gregorb6998662010-01-19 19:34:47 +00002807 return clang_getNullCursor();
2808
2809 case Decl::ObjCForwardProtocol: {
2810 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2811 if (Forward->protocol_size() == 1)
2812 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002813 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002814 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002815
2816 // FIXME: Cannot return multiple definitions.
2817 return clang_getNullCursor();
2818 }
2819
2820 case Decl::ObjCClass: {
2821 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2822 if (Class->size() == 1) {
2823 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2824 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002825 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002826 return clang_getNullCursor();
2827 }
2828
2829 // FIXME: Cannot return multiple definitions.
2830 return clang_getNullCursor();
2831 }
2832
2833 case Decl::Friend:
2834 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002835 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002836 return clang_getNullCursor();
2837
2838 case Decl::FriendTemplate:
2839 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002840 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002841 return clang_getNullCursor();
2842 }
2843
2844 return clang_getNullCursor();
2845}
2846
2847unsigned clang_isCursorDefinition(CXCursor C) {
2848 if (!clang_isDeclaration(C.kind))
2849 return 0;
2850
2851 return clang_getCursorDefinition(C) == C;
2852}
2853
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002854void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002855 const char **startBuf,
2856 const char **endBuf,
2857 unsigned *startLine,
2858 unsigned *startColumn,
2859 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002860 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002861 assert(getCursorDecl(C) && "CXCursor has null decl");
2862 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002863 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2864 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002865
Steve Naroff4ade6d62009-09-23 17:52:52 +00002866 SourceManager &SM = FD->getASTContext().getSourceManager();
2867 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2868 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2869 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2870 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2871 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2872 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2873}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002874
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002875void clang_enableStackTraces(void) {
2876 llvm::sys::PrintStackTraceOnErrorSignal();
2877}
2878
Ted Kremenekfb480492010-01-13 21:46:36 +00002879} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002880
Ted Kremenekfb480492010-01-13 21:46:36 +00002881//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002882// Token-based Operations.
2883//===----------------------------------------------------------------------===//
2884
2885/* CXToken layout:
2886 * int_data[0]: a CXTokenKind
2887 * int_data[1]: starting token location
2888 * int_data[2]: token length
2889 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002890 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002891 * otherwise unused.
2892 */
2893extern "C" {
2894
2895CXTokenKind clang_getTokenKind(CXToken CXTok) {
2896 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2897}
2898
2899CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2900 switch (clang_getTokenKind(CXTok)) {
2901 case CXToken_Identifier:
2902 case CXToken_Keyword:
2903 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002904 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2905 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002906
2907 case CXToken_Literal: {
2908 // We have stashed the starting pointer in the ptr_data field. Use it.
2909 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002910 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002911 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002912
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002913 case CXToken_Punctuation:
2914 case CXToken_Comment:
2915 break;
2916 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002917
2918 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002919 // deconstructing the source location.
2920 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2921 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002922 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002923
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002924 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2925 std::pair<FileID, unsigned> LocInfo
2926 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002927 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002928 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002929 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2930 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002931 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002932
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002933 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002934}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002935
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002936CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2937 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2938 if (!CXXUnit)
2939 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002940
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002941 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2942 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2943}
2944
2945CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2946 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002947 if (!CXXUnit)
2948 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002949
2950 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002951 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2952}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002953
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002954void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2955 CXToken **Tokens, unsigned *NumTokens) {
2956 if (Tokens)
2957 *Tokens = 0;
2958 if (NumTokens)
2959 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002960
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002961 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2962 if (!CXXUnit || !Tokens || !NumTokens)
2963 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002964
Douglas Gregorbdf60622010-03-05 21:16:25 +00002965 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2966
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002967 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002968 if (R.isInvalid())
2969 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002970
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002971 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2972 std::pair<FileID, unsigned> BeginLocInfo
2973 = SourceMgr.getDecomposedLoc(R.getBegin());
2974 std::pair<FileID, unsigned> EndLocInfo
2975 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002976
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002977 // Cannot tokenize across files.
2978 if (BeginLocInfo.first != EndLocInfo.first)
2979 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002980
2981 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002982 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002983 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002984 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002985 if (Invalid)
2986 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002987
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002988 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2989 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002990 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002991 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002992
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002993 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002994 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002995 llvm::SmallVector<CXToken, 32> CXTokens;
2996 Token Tok;
2997 do {
2998 // Lex the next token
2999 Lex.LexFromRawLexer(Tok);
3000 if (Tok.is(tok::eof))
3001 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003002
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003003 // Initialize the CXToken.
3004 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003005
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003006 // - Common fields
3007 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3008 CXTok.int_data[2] = Tok.getLength();
3009 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003010
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003011 // - Kind-specific fields
3012 if (Tok.isLiteral()) {
3013 CXTok.int_data[0] = CXToken_Literal;
3014 CXTok.ptr_data = (void *)Tok.getLiteralData();
3015 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003016 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003017 std::pair<FileID, unsigned> LocInfo
3018 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003019 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003020 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003021 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3022 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003023 return;
3024
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003025 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003026 IdentifierInfo *II
3027 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003028
3029 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3030 CXTok.int_data[0] = CXToken_Keyword;
3031 }
3032 else {
3033 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3034 CXToken_Identifier
3035 : CXToken_Keyword;
3036 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003037 CXTok.ptr_data = II;
3038 } else if (Tok.is(tok::comment)) {
3039 CXTok.int_data[0] = CXToken_Comment;
3040 CXTok.ptr_data = 0;
3041 } else {
3042 CXTok.int_data[0] = CXToken_Punctuation;
3043 CXTok.ptr_data = 0;
3044 }
3045 CXTokens.push_back(CXTok);
3046 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003047
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003048 if (CXTokens.empty())
3049 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003050
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003051 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3052 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3053 *NumTokens = CXTokens.size();
3054}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003055
Ted Kremenek6db61092010-05-05 00:55:15 +00003056void clang_disposeTokens(CXTranslationUnit TU,
3057 CXToken *Tokens, unsigned NumTokens) {
3058 free(Tokens);
3059}
3060
3061} // end: extern "C"
3062
3063//===----------------------------------------------------------------------===//
3064// Token annotation APIs.
3065//===----------------------------------------------------------------------===//
3066
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003067typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003068static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3069 CXCursor parent,
3070 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003071namespace {
3072class AnnotateTokensWorker {
3073 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003074 CXToken *Tokens;
3075 CXCursor *Cursors;
3076 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003077 unsigned TokIdx;
3078 CursorVisitor AnnotateVis;
3079 SourceManager &SrcMgr;
3080
3081 bool MoreTokens() const { return TokIdx < NumTokens; }
3082 unsigned NextToken() const { return TokIdx; }
3083 void AdvanceToken() { ++TokIdx; }
3084 SourceLocation GetTokenLoc(unsigned tokI) {
3085 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3086 }
3087
Ted Kremenek6db61092010-05-05 00:55:15 +00003088public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003089 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003090 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3091 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003092 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003093 NumTokens(numTokens), TokIdx(0),
3094 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3095 Decl::MaxPCHLevel, RegionOfInterest),
3096 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003097
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003098 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003099 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003100 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003101};
3102}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003103
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003104void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3105 // Walk the AST within the region of interest, annotating tokens
3106 // along the way.
3107 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003108
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003109 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3110 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3111 if (Pos != Annotated.end())
3112 Cursors[I] = Pos->second;
3113 }
3114
3115 // Finish up annotating any tokens left.
3116 if (!MoreTokens())
3117 return;
3118
3119 const CXCursor &C = clang_getNullCursor();
3120 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3121 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3122 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003123 }
3124}
3125
Ted Kremenek6db61092010-05-05 00:55:15 +00003126enum CXChildVisitResult
3127AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003128 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3129 // We can always annotate a preprocessing directive/macro instantiation.
3130 if (clang_isPreprocessing(cursor.kind)) {
3131 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003132 return CXChildVisit_Recurse;
3133 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003134
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003135 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003136
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003137 if (cursorRange.isInvalid())
3138 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003139
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003140 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3141
Ted Kremeneka333c662010-05-12 05:29:33 +00003142 // Adjust the annotated range based specific declarations.
3143 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3144 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003145 Decl *D = cxcursor::getCursorDecl(cursor);
3146 // Don't visit synthesized ObjC methods, since they have no syntatic
3147 // representation in the source.
3148 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3149 if (MD->isSynthesized())
3150 return CXChildVisit_Continue;
3151 }
3152 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003153 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3154 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003155 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003156 if (TLoc.isValid() &&
3157 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003158 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003159 }
3160 }
3161 }
3162
Ted Kremenek3f404602010-08-14 01:14:06 +00003163 // If the location of the cursor occurs within a macro instantiation, record
3164 // the spelling location of the cursor in our annotation map. We can then
3165 // paper over the token labelings during a post-processing step to try and
3166 // get cursor mappings for tokens that are the *arguments* of a macro
3167 // instantiation.
3168 if (L.isMacroID()) {
3169 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3170 // Only invalidate the old annotation if it isn't part of a preprocessing
3171 // directive. Here we assume that the default construction of CXCursor
3172 // results in CXCursor.kind being an initialized value (i.e., 0). If
3173 // this isn't the case, we can fix by doing lookup + insertion.
3174
3175 CXCursor &oldC = Annotated[rawEncoding];
3176 if (!clang_isPreprocessing(oldC.kind))
3177 oldC = cursor;
3178 }
3179
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003180 const enum CXCursorKind K = clang_getCursorKind(parent);
3181 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003182 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3183 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003184
3185 while (MoreTokens()) {
3186 const unsigned I = NextToken();
3187 SourceLocation TokLoc = GetTokenLoc(I);
3188 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3189 case RangeBefore:
3190 Cursors[I] = updateC;
3191 AdvanceToken();
3192 continue;
3193 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003194 case RangeOverlap:
3195 break;
3196 }
3197 break;
3198 }
3199
3200 // Visit children to get their cursor information.
3201 const unsigned BeforeChildren = NextToken();
3202 VisitChildren(cursor);
3203 const unsigned AfterChildren = NextToken();
3204
3205 // Adjust 'Last' to the last token within the extent of the cursor.
3206 while (MoreTokens()) {
3207 const unsigned I = NextToken();
3208 SourceLocation TokLoc = GetTokenLoc(I);
3209 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3210 case RangeBefore:
3211 assert(0 && "Infeasible");
3212 case RangeAfter:
3213 break;
3214 case RangeOverlap:
3215 Cursors[I] = updateC;
3216 AdvanceToken();
3217 continue;
3218 }
3219 break;
3220 }
3221 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003222
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003223 // Scan the tokens that are at the beginning of the cursor, but are not
3224 // capture by the child cursors.
3225
3226 // For AST elements within macros, rely on a post-annotate pass to
3227 // to correctly annotate the tokens with cursors. Otherwise we can
3228 // get confusing results of having tokens that map to cursors that really
3229 // are expanded by an instantiation.
3230 if (L.isMacroID())
3231 cursor = clang_getNullCursor();
3232
3233 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3234 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3235 break;
3236 Cursors[I] = cursor;
3237 }
3238 // Scan the tokens that are at the end of the cursor, but are not captured
3239 // but the child cursors.
3240 for (unsigned I = AfterChildren; I != Last; ++I)
3241 Cursors[I] = cursor;
3242
3243 TokIdx = Last;
3244 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003245}
3246
Ted Kremenek6db61092010-05-05 00:55:15 +00003247static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3248 CXCursor parent,
3249 CXClientData client_data) {
3250 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3251}
3252
3253extern "C" {
3254
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003255void clang_annotateTokens(CXTranslationUnit TU,
3256 CXToken *Tokens, unsigned NumTokens,
3257 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003258
3259 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003260 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003261
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003262 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003263 if (!CXXUnit) {
3264 // Any token we don't specifically annotate will have a NULL cursor.
3265 const CXCursor &C = clang_getNullCursor();
3266 for (unsigned I = 0; I != NumTokens; ++I)
3267 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003268 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003269 }
3270
Douglas Gregorbdf60622010-03-05 21:16:25 +00003271 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003272
Douglas Gregor0396f462010-03-19 05:22:59 +00003273 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003274 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003275 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3276 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003277 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3278 clang_getTokenLocation(TU,
3279 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003280
Douglas Gregor0396f462010-03-19 05:22:59 +00003281 // A mapping from the source locations found when re-lexing or traversing the
3282 // region of interest to the corresponding cursors.
3283 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003284
3285 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003286 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003287 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3288 std::pair<FileID, unsigned> BeginLocInfo
3289 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3290 std::pair<FileID, unsigned> EndLocInfo
3291 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003292
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003293 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003294 bool Invalid = false;
3295 if (BeginLocInfo.first == EndLocInfo.first &&
3296 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3297 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003298 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3299 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003300 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003301 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003302 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003303
3304 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003305 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003306 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003307 Token Tok;
3308 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003309
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003310 reprocess:
3311 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3312 // We have found a preprocessing directive. Gobble it up so that we
3313 // don't see it while preprocessing these tokens later, but keep track of
3314 // all of the token locations inside this preprocessing directive so that
3315 // we can annotate them appropriately.
3316 //
3317 // FIXME: Some simple tests here could identify macro definitions and
3318 // #undefs, to provide specific cursor kinds for those.
3319 std::vector<SourceLocation> Locations;
3320 do {
3321 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003322 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003323 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003324
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003325 using namespace cxcursor;
3326 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003327 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3328 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003329 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003330 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3331 Annotated[Locations[I].getRawEncoding()] = Cursor;
3332 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003333
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003334 if (Tok.isAtStartOfLine())
3335 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003336
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003337 continue;
3338 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003339
Douglas Gregor48072312010-03-18 15:23:44 +00003340 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003341 break;
3342 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003343 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003344
Douglas Gregor0396f462010-03-19 05:22:59 +00003345 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003346 // a specific cursor.
3347 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3348 CXXUnit, RegionOfInterest);
3349 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003350}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003351} // end: extern "C"
3352
3353//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003354// Operations for querying linkage of a cursor.
3355//===----------------------------------------------------------------------===//
3356
3357extern "C" {
3358CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003359 if (!clang_isDeclaration(cursor.kind))
3360 return CXLinkage_Invalid;
3361
Ted Kremenek16b42592010-03-03 06:36:57 +00003362 Decl *D = cxcursor::getCursorDecl(cursor);
3363 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3364 switch (ND->getLinkage()) {
3365 case NoLinkage: return CXLinkage_NoLinkage;
3366 case InternalLinkage: return CXLinkage_Internal;
3367 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3368 case ExternalLinkage: return CXLinkage_External;
3369 };
3370
3371 return CXLinkage_Invalid;
3372}
3373} // end: extern "C"
3374
3375//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003376// Operations for querying language of a cursor.
3377//===----------------------------------------------------------------------===//
3378
3379static CXLanguageKind getDeclLanguage(const Decl *D) {
3380 switch (D->getKind()) {
3381 default:
3382 break;
3383 case Decl::ImplicitParam:
3384 case Decl::ObjCAtDefsField:
3385 case Decl::ObjCCategory:
3386 case Decl::ObjCCategoryImpl:
3387 case Decl::ObjCClass:
3388 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003389 case Decl::ObjCForwardProtocol:
3390 case Decl::ObjCImplementation:
3391 case Decl::ObjCInterface:
3392 case Decl::ObjCIvar:
3393 case Decl::ObjCMethod:
3394 case Decl::ObjCProperty:
3395 case Decl::ObjCPropertyImpl:
3396 case Decl::ObjCProtocol:
3397 return CXLanguage_ObjC;
3398 case Decl::CXXConstructor:
3399 case Decl::CXXConversion:
3400 case Decl::CXXDestructor:
3401 case Decl::CXXMethod:
3402 case Decl::CXXRecord:
3403 case Decl::ClassTemplate:
3404 case Decl::ClassTemplatePartialSpecialization:
3405 case Decl::ClassTemplateSpecialization:
3406 case Decl::Friend:
3407 case Decl::FriendTemplate:
3408 case Decl::FunctionTemplate:
3409 case Decl::LinkageSpec:
3410 case Decl::Namespace:
3411 case Decl::NamespaceAlias:
3412 case Decl::NonTypeTemplateParm:
3413 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003414 case Decl::TemplateTemplateParm:
3415 case Decl::TemplateTypeParm:
3416 case Decl::UnresolvedUsingTypename:
3417 case Decl::UnresolvedUsingValue:
3418 case Decl::Using:
3419 case Decl::UsingDirective:
3420 case Decl::UsingShadow:
3421 return CXLanguage_CPlusPlus;
3422 }
3423
3424 return CXLanguage_C;
3425}
3426
3427extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003428
3429enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3430 if (clang_isDeclaration(cursor.kind))
3431 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3432 if (D->hasAttr<UnavailableAttr>() ||
3433 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3434 return CXAvailability_Available;
3435
3436 if (D->hasAttr<DeprecatedAttr>())
3437 return CXAvailability_Deprecated;
3438 }
3439
3440 return CXAvailability_Available;
3441}
3442
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003443CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3444 if (clang_isDeclaration(cursor.kind))
3445 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3446
3447 return CXLanguage_Invalid;
3448}
3449} // end: extern "C"
3450
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003451
3452//===----------------------------------------------------------------------===//
3453// C++ AST instrospection.
3454//===----------------------------------------------------------------------===//
3455
3456extern "C" {
3457unsigned clang_CXXMethod_isStatic(CXCursor C) {
3458 if (!clang_isDeclaration(C.kind))
3459 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003460
3461 CXXMethodDecl *Method = 0;
3462 Decl *D = cxcursor::getCursorDecl(C);
3463 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3464 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3465 else
3466 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3467 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003468}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003469
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003470} // end: extern "C"
3471
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003472//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003473// Attribute introspection.
3474//===----------------------------------------------------------------------===//
3475
3476extern "C" {
3477CXType clang_getIBOutletCollectionType(CXCursor C) {
3478 if (C.kind != CXCursor_IBOutletCollectionAttr)
3479 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3480
3481 IBOutletCollectionAttr *A =
3482 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3483
3484 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3485}
3486} // end: extern "C"
3487
3488//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003489// CXString Operations.
3490//===----------------------------------------------------------------------===//
3491
3492extern "C" {
3493const char *clang_getCString(CXString string) {
3494 return string.Spelling;
3495}
3496
3497void clang_disposeString(CXString string) {
3498 if (string.MustFreeString && string.Spelling)
3499 free((void*)string.Spelling);
3500}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003501
Ted Kremenekfb480492010-01-13 21:46:36 +00003502} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003503
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003504namespace clang { namespace cxstring {
3505CXString createCXString(const char *String, bool DupString){
3506 CXString Str;
3507 if (DupString) {
3508 Str.Spelling = strdup(String);
3509 Str.MustFreeString = 1;
3510 } else {
3511 Str.Spelling = String;
3512 Str.MustFreeString = 0;
3513 }
3514 return Str;
3515}
3516
3517CXString createCXString(llvm::StringRef String, bool DupString) {
3518 CXString Result;
3519 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3520 char *Spelling = (char *)malloc(String.size() + 1);
3521 memmove(Spelling, String.data(), String.size());
3522 Spelling[String.size()] = 0;
3523 Result.Spelling = Spelling;
3524 Result.MustFreeString = 1;
3525 } else {
3526 Result.Spelling = String.data();
3527 Result.MustFreeString = 0;
3528 }
3529 return Result;
3530}
3531}}
3532
Ted Kremenek04bb7162010-01-22 22:44:15 +00003533//===----------------------------------------------------------------------===//
3534// Misc. utility functions.
3535//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003536
Ted Kremenek04bb7162010-01-22 22:44:15 +00003537extern "C" {
3538
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003539CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003540 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003541}
3542
3543} // end: extern "C"