blob: 3c4211efdc50308447661fea7f524f8634e8cc4a [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 Gregorfe72e9c2010-08-31 17:01:39 +0000302 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000303 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000304 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
305 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
306 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
307 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000308 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000309 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
310 bool VisitObjCImplDecl(ObjCImplDecl *D);
311 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
312 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
313 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
314 // etc.
315 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
316 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
317 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000318 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000319 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000320 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000321 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
322
Douglas Gregor01829d32010-08-31 14:41:23 +0000323 // Name visitor
324 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
325
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000326 // Template visitors
327 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000328 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000329 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
330
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000331 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000332 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000333 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000334 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000335 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
336 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000337 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000338 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000339 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000340 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
341 bool VisitPointerTypeLoc(PointerTypeLoc TL);
342 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
343 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
344 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
345 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000346 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000347 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000348 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000349 // FIXME: Implement visitors here when the unimplemented TypeLocs get
350 // implemented
351 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
352 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000353
Douglas Gregora59e3902010-01-21 23:27:09 +0000354 // Statement visitors
355 bool VisitStmt(Stmt *S);
356 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000357 // FIXME: LabelStmt label?
358 bool VisitIfStmt(IfStmt *S);
359 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000360 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000361 bool VisitWhileStmt(WhileStmt *S);
362 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000363// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000364
Douglas Gregor336fd812010-01-23 00:40:08 +0000365 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000366 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
367 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000368 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000369 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000370 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000371 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000372 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000373 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000374 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000375 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000376 // FIXME: AddrLabelExpr (once we have cursors for labels)
377 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
378 bool VisitVAArgExpr(VAArgExpr *E);
379 // FIXME: InitListExpr (for the designators)
380 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000381};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000382
Ted Kremenekab188932010-01-05 19:32:54 +0000383} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000384
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000385static SourceRange getRawCursorExtent(CXCursor C);
386
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000387RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000388 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
389}
390
Douglas Gregorb1373d02010-01-20 20:59:29 +0000391/// \brief Visit the given cursor and, if requested by the visitor,
392/// its children.
393///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000394/// \param Cursor the cursor to visit.
395///
396/// \param CheckRegionOfInterest if true, then the caller already checked that
397/// this cursor is within the region of interest.
398///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000399/// \returns true if the visitation should be aborted, false if it
400/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000401bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000402 if (clang_isInvalid(Cursor.kind))
403 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000404
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405 if (clang_isDeclaration(Cursor.kind)) {
406 Decl *D = getCursorDecl(Cursor);
407 assert(D && "Invalid declaration cursor");
408 if (D->getPCHLevel() > MaxPCHLevel)
409 return false;
410
411 if (D->isImplicit())
412 return false;
413 }
414
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000415 // If we have a range of interest, and this cursor doesn't intersect with it,
416 // we're done.
417 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000418 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000419 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000420 return false;
421 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000422
Douglas Gregorb1373d02010-01-20 20:59:29 +0000423 switch (Visitor(Cursor, Parent, ClientData)) {
424 case CXChildVisit_Break:
425 return true;
426
427 case CXChildVisit_Continue:
428 return false;
429
430 case CXChildVisit_Recurse:
431 return VisitChildren(Cursor);
432 }
433
Douglas Gregorfd643772010-01-25 16:45:46 +0000434 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000435}
436
Douglas Gregor788f5a12010-03-20 00:41:21 +0000437std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
438CursorVisitor::getPreprocessedEntities() {
439 PreprocessingRecord &PPRec
440 = *TU->getPreprocessor().getPreprocessingRecord();
441
442 bool OnlyLocalDecls
443 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
444
445 // There is no region of interest; we have to walk everything.
446 if (RegionOfInterest.isInvalid())
447 return std::make_pair(PPRec.begin(OnlyLocalDecls),
448 PPRec.end(OnlyLocalDecls));
449
450 // Find the file in which the region of interest lands.
451 SourceManager &SM = TU->getSourceManager();
452 std::pair<FileID, unsigned> Begin
453 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
454 std::pair<FileID, unsigned> End
455 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
456
457 // The region of interest spans files; we have to walk everything.
458 if (Begin.first != End.first)
459 return std::make_pair(PPRec.begin(OnlyLocalDecls),
460 PPRec.end(OnlyLocalDecls));
461
462 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
463 = TU->getPreprocessedEntitiesByFile();
464 if (ByFileMap.empty()) {
465 // Build the mapping from files to sets of preprocessed entities.
466 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
467 EEnd = PPRec.end(OnlyLocalDecls);
468 E != EEnd; ++E) {
469 std::pair<FileID, unsigned> P
470 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
471 ByFileMap[P.first].push_back(*E);
472 }
473 }
474
475 return std::make_pair(ByFileMap[Begin.first].begin(),
476 ByFileMap[Begin.first].end());
477}
478
Douglas Gregorb1373d02010-01-20 20:59:29 +0000479/// \brief Visit the children of the given cursor.
480///
481/// \returns true if the visitation should be aborted, false if it
482/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000483bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000484 if (clang_isReference(Cursor.kind)) {
485 // By definition, references have no children.
486 return false;
487 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000488
489 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000490 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000491 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000492
Douglas Gregorb1373d02010-01-20 20:59:29 +0000493 if (clang_isDeclaration(Cursor.kind)) {
494 Decl *D = getCursorDecl(Cursor);
495 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000496 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000497 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000498
Douglas Gregora59e3902010-01-21 23:27:09 +0000499 if (clang_isStatement(Cursor.kind))
500 return Visit(getCursorStmt(Cursor));
501 if (clang_isExpression(Cursor.kind))
502 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000503
Douglas Gregorb1373d02010-01-20 20:59:29 +0000504 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000505 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000506 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
507 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000508 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
509 TLEnd = CXXUnit->top_level_end();
510 TL != TLEnd; ++TL) {
511 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000512 return true;
513 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000514 } else if (VisitDeclContext(
515 CXXUnit->getASTContext().getTranslationUnitDecl()))
516 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000517
Douglas Gregor0396f462010-03-19 05:22:59 +0000518 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000519 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000520 // FIXME: Once we have the ability to deserialize a preprocessing record,
521 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000522 PreprocessingRecord::iterator E, EEnd;
523 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000524 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
525 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
526 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000527
Douglas Gregor0396f462010-03-19 05:22:59 +0000528 continue;
529 }
530
531 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
532 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
533 return true;
534
535 continue;
536 }
537 }
538 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000539 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000540 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000541
Douglas Gregorb1373d02010-01-20 20:59:29 +0000542 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000543 return false;
544}
545
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000546bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000547 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
548 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000549
Ted Kremenek664cffd2010-07-22 11:30:19 +0000550 if (Stmt *Body = B->getBody())
551 return Visit(MakeCXCursor(Body, StmtParent, TU));
552
553 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000554}
555
Douglas Gregorb1373d02010-01-20 20:59:29 +0000556bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000557 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000558 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000559
Ted Kremenek23173d72010-05-18 21:09:07 +0000560 Decl *D = *I;
561 if (D->getLexicalDeclContext() != DC)
562 continue;
563
564 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000565
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000566 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000567 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000568 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000569 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000570
571 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000572 case RangeBefore:
573 // This declaration comes before the region of interest; skip it.
574 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000575
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000576 case RangeAfter:
577 // This declaration comes after the region of interest; we're done.
578 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000579
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000580 case RangeOverlap:
581 // This declaration overlaps the region of interest; visit it.
582 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000583 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000584 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000585
Daniel Dunbard52864b2010-02-14 10:02:57 +0000586 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000587 return true;
588 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000589
Douglas Gregorb1373d02010-01-20 20:59:29 +0000590 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000591}
592
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000593bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
594 llvm_unreachable("Translation units are visited directly by Visit()");
595 return false;
596}
597
598bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
599 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
600 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000601
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000602 return false;
603}
604
605bool CursorVisitor::VisitTagDecl(TagDecl *D) {
606 return VisitDeclContext(D);
607}
608
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000609bool CursorVisitor::VisitClassTemplateSpecializationDecl(
610 ClassTemplateSpecializationDecl *D) {
611 bool ShouldVisitBody = false;
612 switch (D->getSpecializationKind()) {
613 case TSK_Undeclared:
614 case TSK_ImplicitInstantiation:
615 // Nothing to visit
616 return false;
617
618 case TSK_ExplicitInstantiationDeclaration:
619 case TSK_ExplicitInstantiationDefinition:
620 break;
621
622 case TSK_ExplicitSpecialization:
623 ShouldVisitBody = true;
624 break;
625 }
626
627 // Visit the template arguments used in the specialization.
628 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
629 TypeLoc TL = SpecType->getTypeLoc();
630 if (TemplateSpecializationTypeLoc *TSTLoc
631 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
632 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
633 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
634 return true;
635 }
636 }
637
638 if (ShouldVisitBody && VisitCXXRecordDecl(D))
639 return true;
640
641 return false;
642}
643
Douglas Gregor74dbe642010-08-31 19:31:58 +0000644bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
645 ClassTemplatePartialSpecializationDecl *D) {
646 // FIXME: Visit the "outer" template parameter lists on the TagDecl
647 // before visiting these template parameters.
648 if (VisitTemplateParameters(D->getTemplateParameters()))
649 return true;
650
651 // Visit the partial specialization arguments.
652 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
653 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
654 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
655 return true;
656
657 return VisitCXXRecordDecl(D);
658}
659
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000660bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
661 // FIXME: Visit default argument
662 return false;
663}
664
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000665bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
666 if (Expr *Init = D->getInitExpr())
667 return Visit(MakeCXCursor(Init, StmtParent, TU));
668 return false;
669}
670
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000671bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
672 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
673 if (Visit(TSInfo->getTypeLoc()))
674 return true;
675
676 return false;
677}
678
Douglas Gregorb1373d02010-01-20 20:59:29 +0000679bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000680 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
681 // Visit the function declaration's syntactic components in the order
682 // written. This requires a bit of work.
683 TypeLoc TL = TSInfo->getTypeLoc();
684 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
685
686 // If we have a function declared directly (without the use of a typedef),
687 // visit just the return type. Otherwise, just visit the function's type
688 // now.
689 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
690 (!FTL && Visit(TL)))
691 return true;
692
693 // FIXME: Visit the nested-name-specifier, if present.
694
695 // Visit the declaration name.
696 if (VisitDeclarationNameInfo(ND->getNameInfo()))
697 return true;
698
699 // FIXME: Visit explicitly-specified template arguments!
700
701 // Visit the function parameters, if we have a function type.
702 if (FTL && VisitFunctionTypeLoc(*FTL, true))
703 return true;
704
705 // FIXME: Attributes?
706 }
707
Douglas Gregora59e3902010-01-21 23:27:09 +0000708 if (ND->isThisDeclarationADefinition() &&
709 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
710 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000711
Douglas Gregorb1373d02010-01-20 20:59:29 +0000712 return false;
713}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000714
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000715bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
716 if (VisitDeclaratorDecl(D))
717 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000718
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000719 if (Expr *BitWidth = D->getBitWidth())
720 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000721
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000722 return false;
723}
724
725bool CursorVisitor::VisitVarDecl(VarDecl *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 *Init = D->getInit())
730 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000731
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000732 return false;
733}
734
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000735bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
736 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
737 // before visiting these template parameters.
738 if (VisitTemplateParameters(D->getTemplateParameters()))
739 return true;
740
741 return VisitFunctionDecl(D->getTemplatedDecl());
742}
743
Douglas Gregor39d6f072010-08-31 19:02:00 +0000744bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
745 // FIXME: Visit the "outer" template parameter lists on the TagDecl
746 // before visiting these template parameters.
747 if (VisitTemplateParameters(D->getTemplateParameters()))
748 return true;
749
750 return VisitCXXRecordDecl(D->getTemplatedDecl());
751}
752
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000753bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000754 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
755 if (Visit(TSInfo->getTypeLoc()))
756 return true;
757
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000758 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000759 PEnd = ND->param_end();
760 P != PEnd; ++P) {
761 if (Visit(MakeCXCursor(*P, TU)))
762 return true;
763 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000764
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000765 if (ND->isThisDeclarationADefinition() &&
766 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
767 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000768
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000769 return false;
770}
771
Douglas Gregora59e3902010-01-21 23:27:09 +0000772bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
773 return VisitDeclContext(D);
774}
775
Douglas Gregorb1373d02010-01-20 20:59:29 +0000776bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000777 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
778 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000779 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000780
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000781 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
782 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
783 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000784 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000785 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000786
Douglas Gregora59e3902010-01-21 23:27:09 +0000787 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000788}
789
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000790bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
791 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
792 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
793 E = PID->protocol_end(); I != E; ++I, ++PL)
794 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
795 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797 return VisitObjCContainerDecl(PID);
798}
799
Ted Kremenek23173d72010-05-18 21:09:07 +0000800bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000801 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
802 return true;
803
Ted Kremenek23173d72010-05-18 21:09:07 +0000804 // FIXME: This implements a workaround with @property declarations also being
805 // installed in the DeclContext for the @interface. Eventually this code
806 // should be removed.
807 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
808 if (!CDecl || !CDecl->IsClassExtension())
809 return false;
810
811 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
812 if (!ID)
813 return false;
814
815 IdentifierInfo *PropertyId = PD->getIdentifier();
816 ObjCPropertyDecl *prevDecl =
817 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
818
819 if (!prevDecl)
820 return false;
821
822 // Visit synthesized methods since they will be skipped when visiting
823 // the @interface.
824 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
825 if (MD->isSynthesized())
826 if (Visit(MakeCXCursor(MD, TU)))
827 return true;
828
829 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
830 if (MD->isSynthesized())
831 if (Visit(MakeCXCursor(MD, TU)))
832 return true;
833
834 return false;
835}
836
Douglas Gregorb1373d02010-01-20 20:59:29 +0000837bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000838 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000839 if (D->getSuperClass() &&
840 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000841 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000842 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000843 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000844
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000845 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
846 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
847 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000848 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000849 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000850
Douglas Gregora59e3902010-01-21 23:27:09 +0000851 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000852}
853
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
855 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000856}
857
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000858bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000859 // 'ID' could be null when dealing with invalid code.
860 if (ObjCInterfaceDecl *ID = D->getClassInterface())
861 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
862 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000863
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000864 return VisitObjCImplDecl(D);
865}
866
867bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
868#if 0
869 // Issue callbacks for super class.
870 // FIXME: No source location information!
871 if (D->getSuperClass() &&
872 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000873 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000874 TU)))
875 return true;
876#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000877
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000878 return VisitObjCImplDecl(D);
879}
880
881bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
882 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
883 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
884 E = D->protocol_end();
885 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000886 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000887 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000888
889 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000890}
891
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000892bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
893 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
894 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
895 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000896
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000897 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000898}
899
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000900bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
901 return VisitDeclContext(D);
902}
903
Douglas Gregor69319002010-08-31 23:48:11 +0000904bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
905 // FIXME: Visit nested-name-specifier
906
907 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
908 D->getTargetNameLoc(), TU));
909}
910
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000911bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
912 // FIXME: Visit nested-name-specifier
913
914 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
915 D->getIdentLocation(), TU));
916}
917
Douglas Gregor01829d32010-08-31 14:41:23 +0000918bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
919 switch (Name.getName().getNameKind()) {
920 case clang::DeclarationName::Identifier:
921 case clang::DeclarationName::CXXLiteralOperatorName:
922 case clang::DeclarationName::CXXOperatorName:
923 case clang::DeclarationName::CXXUsingDirective:
924 return false;
925
926 case clang::DeclarationName::CXXConstructorName:
927 case clang::DeclarationName::CXXDestructorName:
928 case clang::DeclarationName::CXXConversionFunctionName:
929 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
930 return Visit(TSInfo->getTypeLoc());
931 return false;
932
933 case clang::DeclarationName::ObjCZeroArgSelector:
934 case clang::DeclarationName::ObjCOneArgSelector:
935 case clang::DeclarationName::ObjCMultiArgSelector:
936 // FIXME: Per-identifier location info?
937 return false;
938 }
939
940 return false;
941}
942
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000943bool CursorVisitor::VisitTemplateParameters(
944 const TemplateParameterList *Params) {
945 if (!Params)
946 return false;
947
948 for (TemplateParameterList::const_iterator P = Params->begin(),
949 PEnd = Params->end();
950 P != PEnd; ++P) {
951 if (Visit(MakeCXCursor(*P, TU)))
952 return true;
953 }
954
955 return false;
956}
957
Douglas Gregor0b36e612010-08-31 20:37:03 +0000958bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
959 switch (Name.getKind()) {
960 case TemplateName::Template:
961 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
962
963 case TemplateName::OverloadedTemplate:
964 // FIXME: We need a way to return multiple lookup results in a single
965 // cursor.
966 return false;
967
968 case TemplateName::DependentTemplate:
969 // FIXME: Visit nested-name-specifier.
970 return false;
971
972 case TemplateName::QualifiedTemplate:
973 // FIXME: Visit nested-name-specifier.
974 return Visit(MakeCursorTemplateRef(
975 Name.getAsQualifiedTemplateName()->getDecl(),
976 Loc, TU));
977 }
978
979 return false;
980}
981
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000982bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
983 switch (TAL.getArgument().getKind()) {
984 case TemplateArgument::Null:
985 case TemplateArgument::Integral:
986 return false;
987
988 case TemplateArgument::Pack:
989 // FIXME: Implement when variadic templates come along.
990 return false;
991
992 case TemplateArgument::Type:
993 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
994 return Visit(TSInfo->getTypeLoc());
995 return false;
996
997 case TemplateArgument::Declaration:
998 if (Expr *E = TAL.getSourceDeclExpression())
999 return Visit(MakeCXCursor(E, StmtParent, TU));
1000 return false;
1001
1002 case TemplateArgument::Expression:
1003 if (Expr *E = TAL.getSourceExpression())
1004 return Visit(MakeCXCursor(E, StmtParent, TU));
1005 return false;
1006
1007 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001008 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1009 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001010 }
1011
1012 return false;
1013}
1014
Ted Kremeneka0536d82010-05-07 01:04:29 +00001015bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1016 return VisitDeclContext(D);
1017}
1018
Douglas Gregor01829d32010-08-31 14:41:23 +00001019bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1020 return Visit(TL.getUnqualifiedLoc());
1021}
1022
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001023bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1024 ASTContext &Context = TU->getASTContext();
1025
1026 // Some builtin types (such as Objective-C's "id", "sel", and
1027 // "Class") have associated declarations. Create cursors for those.
1028 QualType VisitType;
1029 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001030 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001031 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001032 case BuiltinType::Char_U:
1033 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001034 case BuiltinType::Char16:
1035 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001036 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001037 case BuiltinType::UInt:
1038 case BuiltinType::ULong:
1039 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001040 case BuiltinType::UInt128:
1041 case BuiltinType::Char_S:
1042 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001043 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001044 case BuiltinType::Short:
1045 case BuiltinType::Int:
1046 case BuiltinType::Long:
1047 case BuiltinType::LongLong:
1048 case BuiltinType::Int128:
1049 case BuiltinType::Float:
1050 case BuiltinType::Double:
1051 case BuiltinType::LongDouble:
1052 case BuiltinType::NullPtr:
1053 case BuiltinType::Overload:
1054 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001055 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001056
1057 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001058 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001059
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001060 case BuiltinType::ObjCId:
1061 VisitType = Context.getObjCIdType();
1062 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001063
1064 case BuiltinType::ObjCClass:
1065 VisitType = Context.getObjCClassType();
1066 break;
1067
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001068 case BuiltinType::ObjCSel:
1069 VisitType = Context.getObjCSelType();
1070 break;
1071 }
1072
1073 if (!VisitType.isNull()) {
1074 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001075 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001076 TU));
1077 }
1078
1079 return false;
1080}
1081
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001082bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1083 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1084}
1085
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001086bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1087 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1088}
1089
1090bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1091 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1092}
1093
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001094bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1095 // FIXME: We can't visit the template template parameter, but there's
1096 // no context information with which we can match up the depth/index in the
1097 // type to the appropriate
1098 return false;
1099}
1100
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001101bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1102 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1103 return true;
1104
John McCallc12c5bb2010-05-15 11:32:37 +00001105 return false;
1106}
1107
1108bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1109 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1110 return true;
1111
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001112 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1113 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1114 TU)))
1115 return true;
1116 }
1117
1118 return false;
1119}
1120
1121bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001122 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001123}
1124
1125bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1126 return Visit(TL.getPointeeLoc());
1127}
1128
1129bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1130 return Visit(TL.getPointeeLoc());
1131}
1132
1133bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1134 return Visit(TL.getPointeeLoc());
1135}
1136
1137bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001138 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001139}
1140
1141bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001142 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001143}
1144
Douglas Gregor01829d32010-08-31 14:41:23 +00001145bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1146 bool SkipResultType) {
1147 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001148 return true;
1149
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001150 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001151 if (Decl *D = TL.getArg(I))
1152 if (Visit(MakeCXCursor(D, TU)))
1153 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001154
1155 return false;
1156}
1157
1158bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1159 if (Visit(TL.getElementLoc()))
1160 return true;
1161
1162 if (Expr *Size = TL.getSizeExpr())
1163 return Visit(MakeCXCursor(Size, StmtParent, TU));
1164
1165 return false;
1166}
1167
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001168bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1169 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001170 // Visit the template name.
1171 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1172 TL.getTemplateNameLoc()))
1173 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001174
1175 // Visit the template arguments.
1176 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1177 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1178 return true;
1179
1180 return false;
1181}
1182
Douglas Gregor2332c112010-01-21 20:48:56 +00001183bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1184 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1185}
1186
1187bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1188 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1189 return Visit(TSInfo->getTypeLoc());
1190
1191 return false;
1192}
1193
Douglas Gregora59e3902010-01-21 23:27:09 +00001194bool CursorVisitor::VisitStmt(Stmt *S) {
1195 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1196 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001197 if (Stmt *C = *Child)
1198 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1199 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001200 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001201
Douglas Gregora59e3902010-01-21 23:27:09 +00001202 return false;
1203}
1204
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001205bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1206 // Specially handle CaseStmts because they can be nested, e.g.:
1207 //
1208 // case 1:
1209 // case 2:
1210 //
1211 // In this case the second CaseStmt is the child of the first. Walking
1212 // these recursively can blow out the stack.
1213 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1214 while (true) {
1215 // Set the Parent field to Cursor, then back to its old value once we're
1216 // done.
1217 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1218
1219 if (Stmt *LHS = S->getLHS())
1220 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1221 return true;
1222 if (Stmt *RHS = S->getRHS())
1223 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1224 return true;
1225 if (Stmt *SubStmt = S->getSubStmt()) {
1226 if (!isa<CaseStmt>(SubStmt))
1227 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1228
1229 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1230 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1231 Cursor = MakeCXCursor(CS, StmtParent, TU);
1232 if (RegionOfInterest.isValid()) {
1233 SourceRange Range = CS->getSourceRange();
1234 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1235 return false;
1236 }
1237
1238 switch (Visitor(Cursor, Parent, ClientData)) {
1239 case CXChildVisit_Break: return true;
1240 case CXChildVisit_Continue: return false;
1241 case CXChildVisit_Recurse:
1242 // Perform tail-recursion manually.
1243 S = CS;
1244 continue;
1245 }
1246 }
1247 return false;
1248 }
1249}
1250
Douglas Gregora59e3902010-01-21 23:27:09 +00001251bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1252 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1253 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001254 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001255 return true;
1256 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001257
Douglas Gregora59e3902010-01-21 23:27:09 +00001258 return false;
1259}
1260
Douglas Gregorf5bab412010-01-22 01:00:11 +00001261bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1262 if (VarDecl *Var = S->getConditionVariable()) {
1263 if (Visit(MakeCXCursor(Var, TU)))
1264 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001265 }
1266
Douglas Gregor263b47b2010-01-25 16:12:32 +00001267 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1268 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001269 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1270 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001271 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1272 return true;
1273
1274 return false;
1275}
1276
1277bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1278 if (VarDecl *Var = S->getConditionVariable()) {
1279 if (Visit(MakeCXCursor(Var, TU)))
1280 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001281 }
1282
Douglas Gregor263b47b2010-01-25 16:12:32 +00001283 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1284 return true;
1285 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1286 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001287
Douglas Gregor263b47b2010-01-25 16:12:32 +00001288 return false;
1289}
1290
1291bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1292 if (VarDecl *Var = S->getConditionVariable()) {
1293 if (Visit(MakeCXCursor(Var, TU)))
1294 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001295 }
1296
Douglas Gregor263b47b2010-01-25 16:12:32 +00001297 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1298 return true;
1299 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001300 return true;
1301
Douglas Gregor263b47b2010-01-25 16:12:32 +00001302 return false;
1303}
1304
1305bool CursorVisitor::VisitForStmt(ForStmt *S) {
1306 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1307 return true;
1308 if (VarDecl *Var = S->getConditionVariable()) {
1309 if (Visit(MakeCXCursor(Var, TU)))
1310 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001311 }
1312
Douglas Gregor263b47b2010-01-25 16:12:32 +00001313 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1314 return true;
1315 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1316 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001317 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1318 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001319
Douglas Gregorf5bab412010-01-22 01:00:11 +00001320 return false;
1321}
1322
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001323bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1324 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1325 return true;
1326
1327 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1328 return true;
1329
1330 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1331 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1332 return true;
1333
1334 return false;
1335}
1336
Ted Kremenek3064ef92010-08-27 21:34:58 +00001337bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1338 if (D->isDefinition()) {
1339 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1340 E = D->bases_end(); I != E; ++I) {
1341 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1342 return true;
1343 }
1344 }
1345
1346 return VisitTagDecl(D);
1347}
1348
1349
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001350bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1351 return Visit(B->getBlockDecl());
1352}
1353
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001354bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1355 // FIXME: Visit fields as well?
1356 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1357 return true;
1358
1359 return VisitExpr(E);
1360}
1361
Douglas Gregor336fd812010-01-23 00:40:08 +00001362bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1363 if (E->isArgumentType()) {
1364 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1365 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001366
Douglas Gregor336fd812010-01-23 00:40:08 +00001367 return false;
1368 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001369
Douglas Gregor336fd812010-01-23 00:40:08 +00001370 return VisitExpr(E);
1371}
1372
1373bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1374 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1375 if (Visit(TSInfo->getTypeLoc()))
1376 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001377
Douglas Gregor336fd812010-01-23 00:40:08 +00001378 return VisitCastExpr(E);
1379}
1380
1381bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1382 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1383 if (Visit(TSInfo->getTypeLoc()))
1384 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001385
Douglas Gregor336fd812010-01-23 00:40:08 +00001386 return VisitExpr(E);
1387}
1388
Douglas Gregor648220e2010-08-10 15:02:34 +00001389bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1390 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1391 Visit(E->getArgTInfo2()->getTypeLoc());
1392}
1393
1394bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1395 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1396 return true;
1397
1398 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1399}
1400
Douglas Gregorc2350e52010-03-08 16:40:19 +00001401bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001402 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1403 if (Visit(TSInfo->getTypeLoc()))
1404 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001405
1406 return VisitExpr(E);
1407}
1408
Douglas Gregor81d34662010-04-20 15:39:42 +00001409bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1410 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1411}
1412
1413
Ted Kremenek09dfa372010-02-18 05:46:33 +00001414bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001415 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1416 i != e; ++i)
1417 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001418 return true;
1419
1420 return false;
1421}
1422
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001423extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001424CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1425 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001426 // We use crash recovery to make some of our APIs more reliable, implicitly
1427 // enable it.
1428 llvm::CrashRecoveryContext::Enable();
1429
Douglas Gregora030b7c2010-01-22 20:35:53 +00001430 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001431 if (excludeDeclarationsFromPCH)
1432 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001433 if (displayDiagnostics)
1434 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001435 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001436}
1437
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001438void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001439 if (CIdx)
1440 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001441 if (getenv("LIBCLANG_TIMING"))
1442 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001443}
1444
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001445void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001446 if (CIdx) {
1447 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1448 CXXIdx->setUseExternalASTGeneration(value);
1449 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001450}
1451
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001452CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001453 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001454 if (!CIdx)
1455 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001456
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001457 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001458
Douglas Gregor28019772010-04-05 23:52:57 +00001459 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001460 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001461 CXXIdx->getOnlyLocalDecls(),
1462 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001463}
1464
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001465unsigned clang_defaultEditingTranslationUnitOptions() {
1466 return CXTranslationUnit_PrecompiledPreamble;
1467}
1468
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001469CXTranslationUnit
1470clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1471 const char *source_filename,
1472 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001473 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001474 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001475 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001476 return clang_parseTranslationUnit(CIdx, source_filename,
1477 command_line_args, num_command_line_args,
1478 unsaved_files, num_unsaved_files,
1479 CXTranslationUnit_DetailedPreprocessingRecord);
1480}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001481
1482struct ParseTranslationUnitInfo {
1483 CXIndex CIdx;
1484 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001485 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001486 int num_command_line_args;
1487 struct CXUnsavedFile *unsaved_files;
1488 unsigned num_unsaved_files;
1489 unsigned options;
1490 CXTranslationUnit result;
1491};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001492static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001493 ParseTranslationUnitInfo *PTUI =
1494 static_cast<ParseTranslationUnitInfo*>(UserData);
1495 CXIndex CIdx = PTUI->CIdx;
1496 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001497 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001498 int num_command_line_args = PTUI->num_command_line_args;
1499 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1500 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1501 unsigned options = PTUI->options;
1502 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001503
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001504 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001505 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001506
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001507 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1508
Douglas Gregor44c181a2010-07-23 00:33:23 +00001509 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001510 bool CompleteTranslationUnit
1511 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001512 bool CacheCodeCompetionResults
1513 = options & CXTranslationUnit_CacheCompletionResults;
1514
Douglas Gregor5352ac02010-01-28 00:27:43 +00001515 // Configure the diagnostics.
1516 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001517 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1518 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001519
Douglas Gregor4db64a42010-01-23 00:14:00 +00001520 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1521 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001522 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001523 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001524 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001525 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1526 Buffer));
1527 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001528
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001529 if (!CXXIdx->getUseExternalASTGeneration()) {
1530 llvm::SmallVector<const char *, 16> Args;
1531
1532 // The 'source_filename' argument is optional. If the caller does not
1533 // specify it then it is assumed that the source file is specified
1534 // in the actual argument list.
1535 if (source_filename)
1536 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001537
1538 // Since the Clang C library is primarily used by batch tools dealing with
1539 // (often very broken) source code, where spell-checking can have a
1540 // significant negative impact on performance (particularly when
1541 // precompiled headers are involved), we disable it by default.
1542 // Note that we place this argument early in the list, so that it can be
1543 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001544 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001545
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001546 Args.insert(Args.end(), command_line_args,
1547 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001548
Douglas Gregor44c181a2010-07-23 00:33:23 +00001549 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001550 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1551 Args.push_back("-Xclang");
1552 Args.push_back("-detailed-preprocessing-record");
1553 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001554
Douglas Gregor5352ac02010-01-28 00:27:43 +00001555 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001556
Ted Kremenek29b72842010-01-07 22:49:05 +00001557#ifdef USE_CRASHTRACER
1558 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001559#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001560
Daniel Dunbar94220972009-12-05 02:17:18 +00001561 llvm::OwningPtr<ASTUnit> Unit(
1562 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001563 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001564 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001565 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001566 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001567 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001568 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001569 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001570 CompleteTranslationUnit,
1571 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001572
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001573 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001574 // Make sure to check that 'Unit' is non-NULL.
1575 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001576 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1577 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001578 D != DEnd; ++D) {
1579 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001580 CXString Msg = clang_formatDiagnostic(&Diag,
1581 clang_defaultDiagnosticDisplayOptions());
1582 fprintf(stderr, "%s\n", clang_getCString(Msg));
1583 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001584 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001585#ifdef LLVM_ON_WIN32
1586 // On Windows, force a flush, since there may be multiple copies of
1587 // stderr and stdout in the file system, all with different buffers
1588 // but writing to the same device.
1589 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001590#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001591 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001592 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001593
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001594 PTUI->result = Unit.take();
1595 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001596 }
1597
Ted Kremenek139ba862009-10-22 00:03:57 +00001598 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001599 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001600
Ted Kremenek139ba862009-10-22 00:03:57 +00001601 // First add the complete path to the 'clang' executable.
1602 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001603 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001604
Ted Kremenek139ba862009-10-22 00:03:57 +00001605 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001606 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001607
Ted Kremenek139ba862009-10-22 00:03:57 +00001608 // The 'source_filename' argument is optional. If the caller does not
1609 // specify it then it is assumed that the source file is specified
1610 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001611 if (source_filename)
1612 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001613
Steve Naroff37b5ac22009-10-15 20:50:09 +00001614 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001615 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001616 char astTmpFile[L_tmpnam];
1617 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001618
1619 // Since the Clang C library is primarily used by batch tools dealing with
1620 // (often very broken) source code, where spell-checking can have a
1621 // significant negative impact on performance (particularly when
1622 // precompiled headers are involved), we disable it by default.
1623 // Note that we place this argument early in the list, so that it can be
1624 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001625 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001626
Douglas Gregor4db64a42010-01-23 00:14:00 +00001627 // Remap any unsaved files to temporary files.
1628 std::vector<llvm::sys::Path> TemporaryFiles;
1629 std::vector<std::string> RemapArgs;
1630 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001631 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001632
Douglas Gregor4db64a42010-01-23 00:14:00 +00001633 // The pointers into the elements of RemapArgs are stable because we
1634 // won't be adding anything to RemapArgs after this point.
1635 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1636 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001637
Ted Kremenek139ba862009-10-22 00:03:57 +00001638 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1639 for (int i = 0; i < num_command_line_args; ++i)
1640 if (const char *arg = command_line_args[i]) {
1641 if (strcmp(arg, "-o") == 0) {
1642 ++i; // Also skip the matching argument.
1643 continue;
1644 }
1645 if (strcmp(arg, "-emit-ast") == 0 ||
1646 strcmp(arg, "-c") == 0 ||
1647 strcmp(arg, "-fsyntax-only") == 0) {
1648 continue;
1649 }
1650
1651 // Keep the argument.
1652 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001653 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001654
Douglas Gregord93256e2010-01-28 06:00:51 +00001655 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001656 char tmpFileResults[L_tmpnam];
1657 char *tmpResultsFileName = tmpnam(tmpFileResults);
1658 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001659 TemporaryFiles.push_back(DiagnosticsFile);
1660 argv.push_back("-fdiagnostics-binary");
1661
Douglas Gregor44c181a2010-07-23 00:33:23 +00001662 // Do we need the detailed preprocessing record?
1663 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1664 argv.push_back("-Xclang");
1665 argv.push_back("-detailed-preprocessing-record");
1666 }
1667
Ted Kremenek139ba862009-10-22 00:03:57 +00001668 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001669 argv.push_back(NULL);
1670
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001671 // Invoke 'clang'.
1672 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1673 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001674 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001675 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1676 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001677 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001678 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001679 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001680
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001681 if (!ErrMsg.empty()) {
1682 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001683 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001684 I != E; ++I) {
1685 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001686 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001687 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001688 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001689
Daniel Dunbar32141c82010-02-23 20:23:45 +00001690 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001691 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001692
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001693 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001694 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001695 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001696 RemappedFiles.size(),
1697 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001698 if (ATU) {
1699 LoadSerializedDiagnostics(DiagnosticsFile,
1700 num_unsaved_files, unsaved_files,
1701 ATU->getFileManager(),
1702 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001703 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001704 } else if (CXXIdx->getDisplayDiagnostics()) {
1705 // We failed to load the ASTUnit, but we can still deserialize the
1706 // diagnostics and emit them.
1707 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001708 Diagnostic Diag;
1709 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001710 // FIXME: Faked LangOpts!
1711 LangOptions LangOpts;
1712 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1713 LoadSerializedDiagnostics(DiagnosticsFile,
1714 num_unsaved_files, unsaved_files,
1715 FileMgr, SourceMgr, Diags);
1716 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1717 DEnd = Diags.end();
1718 D != DEnd; ++D) {
1719 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001720 CXString Msg = clang_formatDiagnostic(&Diag,
1721 clang_defaultDiagnosticDisplayOptions());
1722 fprintf(stderr, "%s\n", clang_getCString(Msg));
1723 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001724 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001725
1726#ifdef LLVM_ON_WIN32
1727 // On Windows, force a flush, since there may be multiple copies of
1728 // stderr and stdout in the file system, all with different buffers
1729 // but writing to the same device.
1730 fflush(stderr);
1731#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001732 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001733
Douglas Gregor313e26c2010-02-18 23:35:40 +00001734 if (ATU) {
1735 // Make the translation unit responsible for destroying all temporary files.
1736 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1737 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001738 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001739 } else {
1740 // Destroy all of the temporary files now; they can't be referenced any
1741 // longer.
1742 llvm::sys::Path(astTmpFile).eraseFromDisk();
1743 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1744 TemporaryFiles[i].eraseFromDisk();
1745 }
1746
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001747 PTUI->result = ATU;
1748}
1749CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1750 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001751 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001752 int num_command_line_args,
1753 struct CXUnsavedFile *unsaved_files,
1754 unsigned num_unsaved_files,
1755 unsigned options) {
1756 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1757 num_command_line_args, unsaved_files, num_unsaved_files,
1758 options, 0 };
1759 llvm::CrashRecoveryContext CRC;
1760
1761 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001762 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1763 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1764 fprintf(stderr, " 'command_line_args' : [");
1765 for (int i = 0; i != num_command_line_args; ++i) {
1766 if (i)
1767 fprintf(stderr, ", ");
1768 fprintf(stderr, "'%s'", command_line_args[i]);
1769 }
1770 fprintf(stderr, "],\n");
1771 fprintf(stderr, " 'unsaved_files' : [");
1772 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1773 if (i)
1774 fprintf(stderr, ", ");
1775 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1776 unsaved_files[i].Length);
1777 }
1778 fprintf(stderr, "],\n");
1779 fprintf(stderr, " 'options' : %d,\n", options);
1780 fprintf(stderr, "}\n");
1781
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001782 return 0;
1783 }
1784
1785 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001786}
1787
Douglas Gregor19998442010-08-13 15:35:05 +00001788unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1789 return CXSaveTranslationUnit_None;
1790}
1791
1792int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1793 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001794 if (!TU)
1795 return 1;
1796
1797 return static_cast<ASTUnit *>(TU)->Save(FileName);
1798}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001799
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001800void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001801 if (CTUnit) {
1802 // If the translation unit has been marked as unsafe to free, just discard
1803 // it.
1804 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1805 return;
1806
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001807 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001808 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001809}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001810
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001811unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1812 return CXReparse_None;
1813}
1814
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001815struct ReparseTranslationUnitInfo {
1816 CXTranslationUnit TU;
1817 unsigned num_unsaved_files;
1818 struct CXUnsavedFile *unsaved_files;
1819 unsigned options;
1820 int result;
1821};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001822static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001823 ReparseTranslationUnitInfo *RTUI =
1824 static_cast<ReparseTranslationUnitInfo*>(UserData);
1825 CXTranslationUnit TU = RTUI->TU;
1826 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1827 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1828 unsigned options = RTUI->options;
1829 (void) options;
1830 RTUI->result = 1;
1831
Douglas Gregorabc563f2010-07-19 21:46:24 +00001832 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001833 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001834
1835 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1836 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1837 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1838 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001839 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001840 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1841 Buffer));
1842 }
1843
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001844 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1845 RemappedFiles.size()))
1846 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001847}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001848int clang_reparseTranslationUnit(CXTranslationUnit TU,
1849 unsigned num_unsaved_files,
1850 struct CXUnsavedFile *unsaved_files,
1851 unsigned options) {
1852 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1853 options, 0 };
1854 llvm::CrashRecoveryContext CRC;
1855
1856 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001857 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001858 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1859 return 1;
1860 }
1861
1862 return RTUI.result;
1863}
1864
Douglas Gregordf95a132010-08-09 20:45:32 +00001865
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001866CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001867 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001868 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001869
Steve Naroff77accc12009-09-03 18:19:54 +00001870 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001871 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001872}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001873
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001874CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001875 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001876 return Result;
1877}
1878
Ted Kremenekfb480492010-01-13 21:46:36 +00001879} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001880
Ted Kremenekfb480492010-01-13 21:46:36 +00001881//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001882// CXSourceLocation and CXSourceRange Operations.
1883//===----------------------------------------------------------------------===//
1884
Douglas Gregorb9790342010-01-22 21:44:22 +00001885extern "C" {
1886CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001887 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001888 return Result;
1889}
1890
1891unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001892 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1893 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1894 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001895}
1896
1897CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1898 CXFile file,
1899 unsigned line,
1900 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001901 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001902 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001903
Douglas Gregorb9790342010-01-22 21:44:22 +00001904 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1905 SourceLocation SLoc
1906 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001907 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001908 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001909
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001910 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001911}
1912
Douglas Gregor5352ac02010-01-28 00:27:43 +00001913CXSourceRange clang_getNullRange() {
1914 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1915 return Result;
1916}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001917
Douglas Gregor5352ac02010-01-28 00:27:43 +00001918CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1919 if (begin.ptr_data[0] != end.ptr_data[0] ||
1920 begin.ptr_data[1] != end.ptr_data[1])
1921 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001922
1923 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001924 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001925 return Result;
1926}
1927
Douglas Gregor46766dc2010-01-26 19:19:08 +00001928void clang_getInstantiationLocation(CXSourceLocation location,
1929 CXFile *file,
1930 unsigned *line,
1931 unsigned *column,
1932 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001933 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1934
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001935 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001936 if (file)
1937 *file = 0;
1938 if (line)
1939 *line = 0;
1940 if (column)
1941 *column = 0;
1942 if (offset)
1943 *offset = 0;
1944 return;
1945 }
1946
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001947 const SourceManager &SM =
1948 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001949 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001950
1951 if (file)
1952 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1953 if (line)
1954 *line = SM.getInstantiationLineNumber(InstLoc);
1955 if (column)
1956 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001957 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001958 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001959}
1960
Douglas Gregor1db19de2010-01-19 21:36:55 +00001961CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001962 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001963 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001964 return Result;
1965}
1966
1967CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001968 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001969 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001970 return Result;
1971}
1972
Douglas Gregorb9790342010-01-22 21:44:22 +00001973} // end: extern "C"
1974
Douglas Gregor1db19de2010-01-19 21:36:55 +00001975//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001976// CXFile Operations.
1977//===----------------------------------------------------------------------===//
1978
1979extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001980CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001981 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001982 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001983
Steve Naroff88145032009-10-27 14:35:18 +00001984 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001985 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001986}
1987
1988time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001989 if (!SFile)
1990 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001991
Steve Naroff88145032009-10-27 14:35:18 +00001992 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1993 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001994}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001995
Douglas Gregorb9790342010-01-22 21:44:22 +00001996CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1997 if (!tu)
1998 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001999
Douglas Gregorb9790342010-01-22 21:44:22 +00002000 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002001
Douglas Gregorb9790342010-01-22 21:44:22 +00002002 FileManager &FMgr = CXXUnit->getFileManager();
2003 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2004 return const_cast<FileEntry *>(File);
2005}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002006
Ted Kremenekfb480492010-01-13 21:46:36 +00002007} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002008
Ted Kremenekfb480492010-01-13 21:46:36 +00002009//===----------------------------------------------------------------------===//
2010// CXCursor Operations.
2011//===----------------------------------------------------------------------===//
2012
Ted Kremenekfb480492010-01-13 21:46:36 +00002013static Decl *getDeclFromExpr(Stmt *E) {
2014 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2015 return RefExpr->getDecl();
2016 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2017 return ME->getMemberDecl();
2018 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2019 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002020
Ted Kremenekfb480492010-01-13 21:46:36 +00002021 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2022 return getDeclFromExpr(CE->getCallee());
2023 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2024 return getDeclFromExpr(CE->getSubExpr());
2025 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2026 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002027
Ted Kremenekfb480492010-01-13 21:46:36 +00002028 return 0;
2029}
2030
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002031static SourceLocation getLocationFromExpr(Expr *E) {
2032 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2033 return /*FIXME:*/Msg->getLeftLoc();
2034 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2035 return DRE->getLocation();
2036 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2037 return Member->getMemberLoc();
2038 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2039 return Ivar->getLocation();
2040 return E->getLocStart();
2041}
2042
Ted Kremenekfb480492010-01-13 21:46:36 +00002043extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002044
2045unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002046 CXCursorVisitor visitor,
2047 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002048 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002049
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002050 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2051 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002052 return CursorVis.VisitChildren(parent);
2053}
2054
Douglas Gregor78205d42010-01-20 21:45:58 +00002055static CXString getDeclSpelling(Decl *D) {
2056 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2057 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002058 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002059
Douglas Gregor78205d42010-01-20 21:45:58 +00002060 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002061 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002062
Douglas Gregor78205d42010-01-20 21:45:58 +00002063 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2064 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2065 // and returns different names. NamedDecl returns the class name and
2066 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002067 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002068
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002069 if (isa<UsingDirectiveDecl>(D))
2070 return createCXString("");
2071
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002072 llvm::SmallString<1024> S;
2073 llvm::raw_svector_ostream os(S);
2074 ND->printName(os);
2075
2076 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002077}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002078
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002079CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002080 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002081 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002082
Steve Narofff334b4e2009-09-02 18:26:48 +00002083 if (clang_isReference(C.kind)) {
2084 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002085 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002086 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002087 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002088 }
2089 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002090 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002091 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002092 }
2093 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002094 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002095 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002096 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002097 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002098 case CXCursor_CXXBaseSpecifier: {
2099 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2100 return createCXString(B->getType().getAsString());
2101 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002102 case CXCursor_TypeRef: {
2103 TypeDecl *Type = getCursorTypeRef(C).first;
2104 assert(Type && "Missing type decl");
2105
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002106 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2107 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002108 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002109 case CXCursor_TemplateRef: {
2110 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002111 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002112
2113 return createCXString(Template->getNameAsString());
2114 }
Douglas Gregor69319002010-08-31 23:48:11 +00002115
2116 case CXCursor_NamespaceRef: {
2117 NamedDecl *NS = getCursorNamespaceRef(C).first;
2118 assert(NS && "Missing namespace decl");
2119
2120 return createCXString(NS->getNameAsString());
2121 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002122
Daniel Dunbaracca7252009-11-30 20:42:49 +00002123 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002124 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002125 }
2126 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002127
2128 if (clang_isExpression(C.kind)) {
2129 Decl *D = getDeclFromExpr(getCursorExpr(C));
2130 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002131 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002132 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002133 }
2134
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002135 if (C.kind == CXCursor_MacroInstantiation)
2136 return createCXString(getCursorMacroInstantiation(C)->getName()
2137 ->getNameStart());
2138
Douglas Gregor572feb22010-03-18 18:04:21 +00002139 if (C.kind == CXCursor_MacroDefinition)
2140 return createCXString(getCursorMacroDefinition(C)->getName()
2141 ->getNameStart());
2142
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002143 if (clang_isDeclaration(C.kind))
2144 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002145
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002146 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002147}
2148
Ted Kremeneke68fff62010-02-17 00:41:32 +00002149CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002150 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002151 case CXCursor_FunctionDecl:
2152 return createCXString("FunctionDecl");
2153 case CXCursor_TypedefDecl:
2154 return createCXString("TypedefDecl");
2155 case CXCursor_EnumDecl:
2156 return createCXString("EnumDecl");
2157 case CXCursor_EnumConstantDecl:
2158 return createCXString("EnumConstantDecl");
2159 case CXCursor_StructDecl:
2160 return createCXString("StructDecl");
2161 case CXCursor_UnionDecl:
2162 return createCXString("UnionDecl");
2163 case CXCursor_ClassDecl:
2164 return createCXString("ClassDecl");
2165 case CXCursor_FieldDecl:
2166 return createCXString("FieldDecl");
2167 case CXCursor_VarDecl:
2168 return createCXString("VarDecl");
2169 case CXCursor_ParmDecl:
2170 return createCXString("ParmDecl");
2171 case CXCursor_ObjCInterfaceDecl:
2172 return createCXString("ObjCInterfaceDecl");
2173 case CXCursor_ObjCCategoryDecl:
2174 return createCXString("ObjCCategoryDecl");
2175 case CXCursor_ObjCProtocolDecl:
2176 return createCXString("ObjCProtocolDecl");
2177 case CXCursor_ObjCPropertyDecl:
2178 return createCXString("ObjCPropertyDecl");
2179 case CXCursor_ObjCIvarDecl:
2180 return createCXString("ObjCIvarDecl");
2181 case CXCursor_ObjCInstanceMethodDecl:
2182 return createCXString("ObjCInstanceMethodDecl");
2183 case CXCursor_ObjCClassMethodDecl:
2184 return createCXString("ObjCClassMethodDecl");
2185 case CXCursor_ObjCImplementationDecl:
2186 return createCXString("ObjCImplementationDecl");
2187 case CXCursor_ObjCCategoryImplDecl:
2188 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002189 case CXCursor_CXXMethod:
2190 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002191 case CXCursor_UnexposedDecl:
2192 return createCXString("UnexposedDecl");
2193 case CXCursor_ObjCSuperClassRef:
2194 return createCXString("ObjCSuperClassRef");
2195 case CXCursor_ObjCProtocolRef:
2196 return createCXString("ObjCProtocolRef");
2197 case CXCursor_ObjCClassRef:
2198 return createCXString("ObjCClassRef");
2199 case CXCursor_TypeRef:
2200 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002201 case CXCursor_TemplateRef:
2202 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002203 case CXCursor_NamespaceRef:
2204 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002205 case CXCursor_UnexposedExpr:
2206 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002207 case CXCursor_BlockExpr:
2208 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002209 case CXCursor_DeclRefExpr:
2210 return createCXString("DeclRefExpr");
2211 case CXCursor_MemberRefExpr:
2212 return createCXString("MemberRefExpr");
2213 case CXCursor_CallExpr:
2214 return createCXString("CallExpr");
2215 case CXCursor_ObjCMessageExpr:
2216 return createCXString("ObjCMessageExpr");
2217 case CXCursor_UnexposedStmt:
2218 return createCXString("UnexposedStmt");
2219 case CXCursor_InvalidFile:
2220 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002221 case CXCursor_InvalidCode:
2222 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002223 case CXCursor_NoDeclFound:
2224 return createCXString("NoDeclFound");
2225 case CXCursor_NotImplemented:
2226 return createCXString("NotImplemented");
2227 case CXCursor_TranslationUnit:
2228 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002229 case CXCursor_UnexposedAttr:
2230 return createCXString("UnexposedAttr");
2231 case CXCursor_IBActionAttr:
2232 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002233 case CXCursor_IBOutletAttr:
2234 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002235 case CXCursor_IBOutletCollectionAttr:
2236 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002237 case CXCursor_PreprocessingDirective:
2238 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002239 case CXCursor_MacroDefinition:
2240 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002241 case CXCursor_MacroInstantiation:
2242 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002243 case CXCursor_Namespace:
2244 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002245 case CXCursor_LinkageSpec:
2246 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002247 case CXCursor_CXXBaseSpecifier:
2248 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002249 case CXCursor_Constructor:
2250 return createCXString("CXXConstructor");
2251 case CXCursor_Destructor:
2252 return createCXString("CXXDestructor");
2253 case CXCursor_ConversionFunction:
2254 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002255 case CXCursor_TemplateTypeParameter:
2256 return createCXString("TemplateTypeParameter");
2257 case CXCursor_NonTypeTemplateParameter:
2258 return createCXString("NonTypeTemplateParameter");
2259 case CXCursor_TemplateTemplateParameter:
2260 return createCXString("TemplateTemplateParameter");
2261 case CXCursor_FunctionTemplate:
2262 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002263 case CXCursor_ClassTemplate:
2264 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002265 case CXCursor_ClassTemplatePartialSpecialization:
2266 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002267 case CXCursor_NamespaceAlias:
2268 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002269 case CXCursor_UsingDirective:
2270 return createCXString("UsingDirective");
Steve Naroff89922f82009-08-31 00:59:03 +00002271 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002272
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002273 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002274 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002275}
Steve Naroff89922f82009-08-31 00:59:03 +00002276
Ted Kremeneke68fff62010-02-17 00:41:32 +00002277enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2278 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002279 CXClientData client_data) {
2280 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2281 *BestCursor = cursor;
2282 return CXChildVisit_Recurse;
2283}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002284
Douglas Gregorb9790342010-01-22 21:44:22 +00002285CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2286 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002287 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002288
Douglas Gregorb9790342010-01-22 21:44:22 +00002289 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002290 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2291
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002292 // Translate the given source location to make it point at the beginning of
2293 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002294 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002295
2296 // Guard against an invalid SourceLocation, or we may assert in one
2297 // of the following calls.
2298 if (SLoc.isInvalid())
2299 return clang_getNullCursor();
2300
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002301 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2302 CXXUnit->getASTContext().getLangOptions());
2303
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002304 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2305 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002306 // FIXME: Would be great to have a "hint" cursor, then walk from that
2307 // hint cursor upward until we find a cursor whose source range encloses
2308 // the region of interest, rather than starting from the translation unit.
2309 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002310 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002311 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002312 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002313 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002314 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002315}
2316
Ted Kremenek73885552009-11-17 19:28:59 +00002317CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002318 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002319}
2320
2321unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002322 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002323}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002324
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002325unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002326 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2327}
2328
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002329unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002330 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2331}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002332
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002333unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002334 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2335}
2336
Douglas Gregor97b98722010-01-19 23:20:36 +00002337unsigned clang_isExpression(enum CXCursorKind K) {
2338 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2339}
2340
2341unsigned clang_isStatement(enum CXCursorKind K) {
2342 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2343}
2344
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002345unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2346 return K == CXCursor_TranslationUnit;
2347}
2348
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002349unsigned clang_isPreprocessing(enum CXCursorKind K) {
2350 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2351}
2352
Ted Kremenekad6eff62010-03-08 21:17:29 +00002353unsigned clang_isUnexposed(enum CXCursorKind K) {
2354 switch (K) {
2355 case CXCursor_UnexposedDecl:
2356 case CXCursor_UnexposedExpr:
2357 case CXCursor_UnexposedStmt:
2358 case CXCursor_UnexposedAttr:
2359 return true;
2360 default:
2361 return false;
2362 }
2363}
2364
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002365CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002366 return C.kind;
2367}
2368
Douglas Gregor98258af2010-01-18 22:46:11 +00002369CXSourceLocation clang_getCursorLocation(CXCursor C) {
2370 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002371 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002372 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002373 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2374 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002375 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002376 }
2377
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002378 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002379 std::pair<ObjCProtocolDecl *, SourceLocation> P
2380 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002381 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002382 }
2383
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002384 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002385 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2386 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002387 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002388 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002389
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002390 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002391 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002392 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002393 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002394
2395 case CXCursor_TemplateRef: {
2396 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2397 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2398 }
2399
Douglas Gregor69319002010-08-31 23:48:11 +00002400 case CXCursor_NamespaceRef: {
2401 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2402 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2403 }
2404
Ted Kremenek3064ef92010-08-27 21:34:58 +00002405 case CXCursor_CXXBaseSpecifier: {
2406 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2407 return clang_getNullLocation();
2408 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002409
Douglas Gregorf46034a2010-01-18 23:41:10 +00002410 default:
2411 // FIXME: Need a way to enumerate all non-reference cases.
2412 llvm_unreachable("Missed a reference kind");
2413 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002414 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002415
2416 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002417 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002418 getLocationFromExpr(getCursorExpr(C)));
2419
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002420 if (C.kind == CXCursor_PreprocessingDirective) {
2421 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2422 return cxloc::translateSourceLocation(getCursorContext(C), L);
2423 }
Douglas Gregor48072312010-03-18 15:23:44 +00002424
2425 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002426 SourceLocation L
2427 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002428 return cxloc::translateSourceLocation(getCursorContext(C), L);
2429 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002430
2431 if (C.kind == CXCursor_MacroDefinition) {
2432 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2433 return cxloc::translateSourceLocation(getCursorContext(C), L);
2434 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002435
Ted Kremenek9a700d22010-05-12 06:16:13 +00002436 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002437 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002438
Douglas Gregorf46034a2010-01-18 23:41:10 +00002439 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002440 SourceLocation Loc = D->getLocation();
2441 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2442 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002443 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002444}
Douglas Gregora7bde202010-01-19 00:34:46 +00002445
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002446} // end extern "C"
2447
2448static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002449 if (clang_isReference(C.kind)) {
2450 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002451 case CXCursor_ObjCSuperClassRef:
2452 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002453
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002454 case CXCursor_ObjCProtocolRef:
2455 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002456
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002457 case CXCursor_ObjCClassRef:
2458 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002459
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002460 case CXCursor_TypeRef:
2461 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002462
2463 case CXCursor_TemplateRef:
2464 return getCursorTemplateRef(C).second;
2465
Douglas Gregor69319002010-08-31 23:48:11 +00002466 case CXCursor_NamespaceRef:
2467 return getCursorNamespaceRef(C).second;
2468
Ted Kremenek3064ef92010-08-27 21:34:58 +00002469 case CXCursor_CXXBaseSpecifier:
2470 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2471 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002472
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002473 default:
2474 // FIXME: Need a way to enumerate all non-reference cases.
2475 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002476 }
2477 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002478
2479 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002480 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002481
2482 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002483 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002484
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002485 if (C.kind == CXCursor_PreprocessingDirective)
2486 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002487
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002488 if (C.kind == CXCursor_MacroInstantiation)
2489 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002490
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002491 if (C.kind == CXCursor_MacroDefinition)
2492 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002493
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002494 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2495 return getCursorDecl(C)->getSourceRange();
2496
2497 return SourceRange();
2498}
2499
2500extern "C" {
2501
2502CXSourceRange clang_getCursorExtent(CXCursor C) {
2503 SourceRange R = getRawCursorExtent(C);
2504 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002505 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002506
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002507 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002508}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002509
2510CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002511 if (clang_isInvalid(C.kind))
2512 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002513
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002514 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002515 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002516 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002517
Douglas Gregor97b98722010-01-19 23:20:36 +00002518 if (clang_isExpression(C.kind)) {
2519 Decl *D = getDeclFromExpr(getCursorExpr(C));
2520 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002521 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002522 return clang_getNullCursor();
2523 }
2524
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002525 if (C.kind == CXCursor_MacroInstantiation) {
2526 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2527 return MakeMacroDefinitionCursor(Def, CXXUnit);
2528 }
2529
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002530 if (!clang_isReference(C.kind))
2531 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002532
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002533 switch (C.kind) {
2534 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002535 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002536
2537 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002538 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002539
2540 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002541 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002542
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002543 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002544 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002545
2546 case CXCursor_TemplateRef:
2547 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2548
Douglas Gregor69319002010-08-31 23:48:11 +00002549 case CXCursor_NamespaceRef:
2550 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2551
Ted Kremenek3064ef92010-08-27 21:34:58 +00002552 case CXCursor_CXXBaseSpecifier: {
2553 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2554 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2555 CXXUnit));
2556 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002557
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002558 default:
2559 // We would prefer to enumerate all non-reference cursor kinds here.
2560 llvm_unreachable("Unhandled reference cursor kind");
2561 break;
2562 }
2563 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002564
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002565 return clang_getNullCursor();
2566}
2567
Douglas Gregorb6998662010-01-19 19:34:47 +00002568CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002569 if (clang_isInvalid(C.kind))
2570 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002571
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002572 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002573
Douglas Gregorb6998662010-01-19 19:34:47 +00002574 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002575 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002576 C = clang_getCursorReferenced(C);
2577 WasReference = true;
2578 }
2579
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002580 if (C.kind == CXCursor_MacroInstantiation)
2581 return clang_getCursorReferenced(C);
2582
Douglas Gregorb6998662010-01-19 19:34:47 +00002583 if (!clang_isDeclaration(C.kind))
2584 return clang_getNullCursor();
2585
2586 Decl *D = getCursorDecl(C);
2587 if (!D)
2588 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002589
Douglas Gregorb6998662010-01-19 19:34:47 +00002590 switch (D->getKind()) {
2591 // Declaration kinds that don't really separate the notions of
2592 // declaration and definition.
2593 case Decl::Namespace:
2594 case Decl::Typedef:
2595 case Decl::TemplateTypeParm:
2596 case Decl::EnumConstant:
2597 case Decl::Field:
2598 case Decl::ObjCIvar:
2599 case Decl::ObjCAtDefsField:
2600 case Decl::ImplicitParam:
2601 case Decl::ParmVar:
2602 case Decl::NonTypeTemplateParm:
2603 case Decl::TemplateTemplateParm:
2604 case Decl::ObjCCategoryImpl:
2605 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002606 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002607 case Decl::LinkageSpec:
2608 case Decl::ObjCPropertyImpl:
2609 case Decl::FileScopeAsm:
2610 case Decl::StaticAssert:
2611 case Decl::Block:
2612 return C;
2613
2614 // Declaration kinds that don't make any sense here, but are
2615 // nonetheless harmless.
2616 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002617 break;
2618
2619 // Declaration kinds for which the definition is not resolvable.
2620 case Decl::UnresolvedUsingTypename:
2621 case Decl::UnresolvedUsingValue:
2622 break;
2623
2624 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002625 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2626 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002627
2628 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002629 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002630
2631 case Decl::Enum:
2632 case Decl::Record:
2633 case Decl::CXXRecord:
2634 case Decl::ClassTemplateSpecialization:
2635 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002636 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002637 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002638 return clang_getNullCursor();
2639
2640 case Decl::Function:
2641 case Decl::CXXMethod:
2642 case Decl::CXXConstructor:
2643 case Decl::CXXDestructor:
2644 case Decl::CXXConversion: {
2645 const FunctionDecl *Def = 0;
2646 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002647 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002648 return clang_getNullCursor();
2649 }
2650
2651 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002652 // Ask the variable if it has a definition.
2653 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2654 return MakeCXCursor(Def, CXXUnit);
2655 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002656 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002657
Douglas Gregorb6998662010-01-19 19:34:47 +00002658 case Decl::FunctionTemplate: {
2659 const FunctionDecl *Def = 0;
2660 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002661 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002662 return clang_getNullCursor();
2663 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002664
Douglas Gregorb6998662010-01-19 19:34:47 +00002665 case Decl::ClassTemplate: {
2666 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002667 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002668 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002669 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002670 return clang_getNullCursor();
2671 }
2672
2673 case Decl::Using: {
2674 UsingDecl *Using = cast<UsingDecl>(D);
2675 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002676 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2677 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002678 S != SEnd; ++S) {
2679 if (Def != clang_getNullCursor()) {
2680 // FIXME: We have no way to return multiple results.
2681 return clang_getNullCursor();
2682 }
2683
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002684 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002685 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002686 }
2687
2688 return Def;
2689 }
2690
2691 case Decl::UsingShadow:
2692 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002693 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002694 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002695
2696 case Decl::ObjCMethod: {
2697 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2698 if (Method->isThisDeclarationADefinition())
2699 return C;
2700
2701 // Dig out the method definition in the associated
2702 // @implementation, if we have it.
2703 // FIXME: The ASTs should make finding the definition easier.
2704 if (ObjCInterfaceDecl *Class
2705 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2706 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2707 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2708 Method->isInstanceMethod()))
2709 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002710 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002711
2712 return clang_getNullCursor();
2713 }
2714
2715 case Decl::ObjCCategory:
2716 if (ObjCCategoryImplDecl *Impl
2717 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002718 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002719 return clang_getNullCursor();
2720
2721 case Decl::ObjCProtocol:
2722 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2723 return C;
2724 return clang_getNullCursor();
2725
2726 case Decl::ObjCInterface:
2727 // There are two notions of a "definition" for an Objective-C
2728 // class: the interface and its implementation. When we resolved a
2729 // reference to an Objective-C class, produce the @interface as
2730 // the definition; when we were provided with the interface,
2731 // produce the @implementation as the definition.
2732 if (WasReference) {
2733 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2734 return C;
2735 } else if (ObjCImplementationDecl *Impl
2736 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002737 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002738 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002739
Douglas Gregorb6998662010-01-19 19:34:47 +00002740 case Decl::ObjCProperty:
2741 // FIXME: We don't really know where to find the
2742 // ObjCPropertyImplDecls that implement this property.
2743 return clang_getNullCursor();
2744
2745 case Decl::ObjCCompatibleAlias:
2746 if (ObjCInterfaceDecl *Class
2747 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2748 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002749 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002750
Douglas Gregorb6998662010-01-19 19:34:47 +00002751 return clang_getNullCursor();
2752
2753 case Decl::ObjCForwardProtocol: {
2754 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2755 if (Forward->protocol_size() == 1)
2756 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002757 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002758 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002759
2760 // FIXME: Cannot return multiple definitions.
2761 return clang_getNullCursor();
2762 }
2763
2764 case Decl::ObjCClass: {
2765 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2766 if (Class->size() == 1) {
2767 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2768 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002769 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002770 return clang_getNullCursor();
2771 }
2772
2773 // FIXME: Cannot return multiple definitions.
2774 return clang_getNullCursor();
2775 }
2776
2777 case Decl::Friend:
2778 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002779 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002780 return clang_getNullCursor();
2781
2782 case Decl::FriendTemplate:
2783 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002784 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002785 return clang_getNullCursor();
2786 }
2787
2788 return clang_getNullCursor();
2789}
2790
2791unsigned clang_isCursorDefinition(CXCursor C) {
2792 if (!clang_isDeclaration(C.kind))
2793 return 0;
2794
2795 return clang_getCursorDefinition(C) == C;
2796}
2797
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002798void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002799 const char **startBuf,
2800 const char **endBuf,
2801 unsigned *startLine,
2802 unsigned *startColumn,
2803 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002804 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002805 assert(getCursorDecl(C) && "CXCursor has null decl");
2806 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002807 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2808 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002809
Steve Naroff4ade6d62009-09-23 17:52:52 +00002810 SourceManager &SM = FD->getASTContext().getSourceManager();
2811 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2812 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2813 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2814 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2815 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2816 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2817}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002818
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002819void clang_enableStackTraces(void) {
2820 llvm::sys::PrintStackTraceOnErrorSignal();
2821}
2822
Ted Kremenekfb480492010-01-13 21:46:36 +00002823} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002824
Ted Kremenekfb480492010-01-13 21:46:36 +00002825//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002826// Token-based Operations.
2827//===----------------------------------------------------------------------===//
2828
2829/* CXToken layout:
2830 * int_data[0]: a CXTokenKind
2831 * int_data[1]: starting token location
2832 * int_data[2]: token length
2833 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002834 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002835 * otherwise unused.
2836 */
2837extern "C" {
2838
2839CXTokenKind clang_getTokenKind(CXToken CXTok) {
2840 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2841}
2842
2843CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2844 switch (clang_getTokenKind(CXTok)) {
2845 case CXToken_Identifier:
2846 case CXToken_Keyword:
2847 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002848 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2849 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002850
2851 case CXToken_Literal: {
2852 // We have stashed the starting pointer in the ptr_data field. Use it.
2853 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002854 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002855 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002856
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002857 case CXToken_Punctuation:
2858 case CXToken_Comment:
2859 break;
2860 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002861
2862 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002863 // deconstructing the source location.
2864 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2865 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002866 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002867
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002868 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2869 std::pair<FileID, unsigned> LocInfo
2870 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002871 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002872 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002873 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2874 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002875 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002876
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002877 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002878}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002879
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002880CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2881 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2882 if (!CXXUnit)
2883 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002884
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002885 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2886 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2887}
2888
2889CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2890 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002891 if (!CXXUnit)
2892 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002893
2894 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002895 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2896}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002897
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002898void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2899 CXToken **Tokens, unsigned *NumTokens) {
2900 if (Tokens)
2901 *Tokens = 0;
2902 if (NumTokens)
2903 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002904
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002905 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2906 if (!CXXUnit || !Tokens || !NumTokens)
2907 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002908
Douglas Gregorbdf60622010-03-05 21:16:25 +00002909 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2910
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002911 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002912 if (R.isInvalid())
2913 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002914
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002915 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2916 std::pair<FileID, unsigned> BeginLocInfo
2917 = SourceMgr.getDecomposedLoc(R.getBegin());
2918 std::pair<FileID, unsigned> EndLocInfo
2919 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002920
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002921 // Cannot tokenize across files.
2922 if (BeginLocInfo.first != EndLocInfo.first)
2923 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002924
2925 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002926 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002927 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002928 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002929 if (Invalid)
2930 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002931
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002932 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2933 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002934 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002935 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002936
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002937 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002938 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002939 llvm::SmallVector<CXToken, 32> CXTokens;
2940 Token Tok;
2941 do {
2942 // Lex the next token
2943 Lex.LexFromRawLexer(Tok);
2944 if (Tok.is(tok::eof))
2945 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002946
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002947 // Initialize the CXToken.
2948 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002949
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002950 // - Common fields
2951 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2952 CXTok.int_data[2] = Tok.getLength();
2953 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002954
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002955 // - Kind-specific fields
2956 if (Tok.isLiteral()) {
2957 CXTok.int_data[0] = CXToken_Literal;
2958 CXTok.ptr_data = (void *)Tok.getLiteralData();
2959 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002960 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002961 std::pair<FileID, unsigned> LocInfo
2962 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002963 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002964 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002965 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2966 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002967 return;
2968
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002969 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002970 IdentifierInfo *II
2971 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002972
2973 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2974 CXTok.int_data[0] = CXToken_Keyword;
2975 }
2976 else {
2977 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2978 CXToken_Identifier
2979 : CXToken_Keyword;
2980 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002981 CXTok.ptr_data = II;
2982 } else if (Tok.is(tok::comment)) {
2983 CXTok.int_data[0] = CXToken_Comment;
2984 CXTok.ptr_data = 0;
2985 } else {
2986 CXTok.int_data[0] = CXToken_Punctuation;
2987 CXTok.ptr_data = 0;
2988 }
2989 CXTokens.push_back(CXTok);
2990 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002991
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002992 if (CXTokens.empty())
2993 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002994
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002995 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2996 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2997 *NumTokens = CXTokens.size();
2998}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002999
Ted Kremenek6db61092010-05-05 00:55:15 +00003000void clang_disposeTokens(CXTranslationUnit TU,
3001 CXToken *Tokens, unsigned NumTokens) {
3002 free(Tokens);
3003}
3004
3005} // end: extern "C"
3006
3007//===----------------------------------------------------------------------===//
3008// Token annotation APIs.
3009//===----------------------------------------------------------------------===//
3010
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003011typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003012static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3013 CXCursor parent,
3014 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003015namespace {
3016class AnnotateTokensWorker {
3017 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003018 CXToken *Tokens;
3019 CXCursor *Cursors;
3020 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003021 unsigned TokIdx;
3022 CursorVisitor AnnotateVis;
3023 SourceManager &SrcMgr;
3024
3025 bool MoreTokens() const { return TokIdx < NumTokens; }
3026 unsigned NextToken() const { return TokIdx; }
3027 void AdvanceToken() { ++TokIdx; }
3028 SourceLocation GetTokenLoc(unsigned tokI) {
3029 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3030 }
3031
Ted Kremenek6db61092010-05-05 00:55:15 +00003032public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003033 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003034 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3035 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003036 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003037 NumTokens(numTokens), TokIdx(0),
3038 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3039 Decl::MaxPCHLevel, RegionOfInterest),
3040 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003041
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003042 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003043 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003044 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003045};
3046}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003047
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003048void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3049 // Walk the AST within the region of interest, annotating tokens
3050 // along the way.
3051 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003052
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003053 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3054 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3055 if (Pos != Annotated.end())
3056 Cursors[I] = Pos->second;
3057 }
3058
3059 // Finish up annotating any tokens left.
3060 if (!MoreTokens())
3061 return;
3062
3063 const CXCursor &C = clang_getNullCursor();
3064 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3065 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3066 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003067 }
3068}
3069
Ted Kremenek6db61092010-05-05 00:55:15 +00003070enum CXChildVisitResult
3071AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003072 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3073 // We can always annotate a preprocessing directive/macro instantiation.
3074 if (clang_isPreprocessing(cursor.kind)) {
3075 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003076 return CXChildVisit_Recurse;
3077 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003078
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003079 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003080
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003081 if (cursorRange.isInvalid())
3082 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003083
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003084 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3085
Ted Kremeneka333c662010-05-12 05:29:33 +00003086 // Adjust the annotated range based specific declarations.
3087 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3088 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003089 Decl *D = cxcursor::getCursorDecl(cursor);
3090 // Don't visit synthesized ObjC methods, since they have no syntatic
3091 // representation in the source.
3092 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3093 if (MD->isSynthesized())
3094 return CXChildVisit_Continue;
3095 }
3096 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003097 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3098 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003099 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003100 if (TLoc.isValid() &&
3101 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003102 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003103 }
3104 }
3105 }
3106
Ted Kremenek3f404602010-08-14 01:14:06 +00003107 // If the location of the cursor occurs within a macro instantiation, record
3108 // the spelling location of the cursor in our annotation map. We can then
3109 // paper over the token labelings during a post-processing step to try and
3110 // get cursor mappings for tokens that are the *arguments* of a macro
3111 // instantiation.
3112 if (L.isMacroID()) {
3113 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3114 // Only invalidate the old annotation if it isn't part of a preprocessing
3115 // directive. Here we assume that the default construction of CXCursor
3116 // results in CXCursor.kind being an initialized value (i.e., 0). If
3117 // this isn't the case, we can fix by doing lookup + insertion.
3118
3119 CXCursor &oldC = Annotated[rawEncoding];
3120 if (!clang_isPreprocessing(oldC.kind))
3121 oldC = cursor;
3122 }
3123
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003124 const enum CXCursorKind K = clang_getCursorKind(parent);
3125 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003126 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3127 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003128
3129 while (MoreTokens()) {
3130 const unsigned I = NextToken();
3131 SourceLocation TokLoc = GetTokenLoc(I);
3132 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3133 case RangeBefore:
3134 Cursors[I] = updateC;
3135 AdvanceToken();
3136 continue;
3137 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003138 case RangeOverlap:
3139 break;
3140 }
3141 break;
3142 }
3143
3144 // Visit children to get their cursor information.
3145 const unsigned BeforeChildren = NextToken();
3146 VisitChildren(cursor);
3147 const unsigned AfterChildren = NextToken();
3148
3149 // Adjust 'Last' to the last token within the extent of the cursor.
3150 while (MoreTokens()) {
3151 const unsigned I = NextToken();
3152 SourceLocation TokLoc = GetTokenLoc(I);
3153 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3154 case RangeBefore:
3155 assert(0 && "Infeasible");
3156 case RangeAfter:
3157 break;
3158 case RangeOverlap:
3159 Cursors[I] = updateC;
3160 AdvanceToken();
3161 continue;
3162 }
3163 break;
3164 }
3165 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003166
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003167 // Scan the tokens that are at the beginning of the cursor, but are not
3168 // capture by the child cursors.
3169
3170 // For AST elements within macros, rely on a post-annotate pass to
3171 // to correctly annotate the tokens with cursors. Otherwise we can
3172 // get confusing results of having tokens that map to cursors that really
3173 // are expanded by an instantiation.
3174 if (L.isMacroID())
3175 cursor = clang_getNullCursor();
3176
3177 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3178 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3179 break;
3180 Cursors[I] = cursor;
3181 }
3182 // Scan the tokens that are at the end of the cursor, but are not captured
3183 // but the child cursors.
3184 for (unsigned I = AfterChildren; I != Last; ++I)
3185 Cursors[I] = cursor;
3186
3187 TokIdx = Last;
3188 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003189}
3190
Ted Kremenek6db61092010-05-05 00:55:15 +00003191static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3192 CXCursor parent,
3193 CXClientData client_data) {
3194 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3195}
3196
3197extern "C" {
3198
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003199void clang_annotateTokens(CXTranslationUnit TU,
3200 CXToken *Tokens, unsigned NumTokens,
3201 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003202
3203 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003204 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003205
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003206 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003207 if (!CXXUnit) {
3208 // Any token we don't specifically annotate will have a NULL cursor.
3209 const CXCursor &C = clang_getNullCursor();
3210 for (unsigned I = 0; I != NumTokens; ++I)
3211 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003212 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003213 }
3214
Douglas Gregorbdf60622010-03-05 21:16:25 +00003215 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003216
Douglas Gregor0396f462010-03-19 05:22:59 +00003217 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003218 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003219 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3220 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003221 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3222 clang_getTokenLocation(TU,
3223 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003224
Douglas Gregor0396f462010-03-19 05:22:59 +00003225 // A mapping from the source locations found when re-lexing or traversing the
3226 // region of interest to the corresponding cursors.
3227 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003228
3229 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003230 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003231 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3232 std::pair<FileID, unsigned> BeginLocInfo
3233 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3234 std::pair<FileID, unsigned> EndLocInfo
3235 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003236
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003237 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003238 bool Invalid = false;
3239 if (BeginLocInfo.first == EndLocInfo.first &&
3240 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3241 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003242 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3243 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003244 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003245 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003246 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003247
3248 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003249 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003250 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003251 Token Tok;
3252 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003253
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003254 reprocess:
3255 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3256 // We have found a preprocessing directive. Gobble it up so that we
3257 // don't see it while preprocessing these tokens later, but keep track of
3258 // all of the token locations inside this preprocessing directive so that
3259 // we can annotate them appropriately.
3260 //
3261 // FIXME: Some simple tests here could identify macro definitions and
3262 // #undefs, to provide specific cursor kinds for those.
3263 std::vector<SourceLocation> Locations;
3264 do {
3265 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003266 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003267 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003268
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003269 using namespace cxcursor;
3270 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003271 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3272 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003273 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003274 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3275 Annotated[Locations[I].getRawEncoding()] = Cursor;
3276 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003277
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003278 if (Tok.isAtStartOfLine())
3279 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003280
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003281 continue;
3282 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003283
Douglas Gregor48072312010-03-18 15:23:44 +00003284 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003285 break;
3286 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003287 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003288
Douglas Gregor0396f462010-03-19 05:22:59 +00003289 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003290 // a specific cursor.
3291 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3292 CXXUnit, RegionOfInterest);
3293 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003294}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003295} // end: extern "C"
3296
3297//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003298// Operations for querying linkage of a cursor.
3299//===----------------------------------------------------------------------===//
3300
3301extern "C" {
3302CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003303 if (!clang_isDeclaration(cursor.kind))
3304 return CXLinkage_Invalid;
3305
Ted Kremenek16b42592010-03-03 06:36:57 +00003306 Decl *D = cxcursor::getCursorDecl(cursor);
3307 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3308 switch (ND->getLinkage()) {
3309 case NoLinkage: return CXLinkage_NoLinkage;
3310 case InternalLinkage: return CXLinkage_Internal;
3311 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3312 case ExternalLinkage: return CXLinkage_External;
3313 };
3314
3315 return CXLinkage_Invalid;
3316}
3317} // end: extern "C"
3318
3319//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003320// Operations for querying language of a cursor.
3321//===----------------------------------------------------------------------===//
3322
3323static CXLanguageKind getDeclLanguage(const Decl *D) {
3324 switch (D->getKind()) {
3325 default:
3326 break;
3327 case Decl::ImplicitParam:
3328 case Decl::ObjCAtDefsField:
3329 case Decl::ObjCCategory:
3330 case Decl::ObjCCategoryImpl:
3331 case Decl::ObjCClass:
3332 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003333 case Decl::ObjCForwardProtocol:
3334 case Decl::ObjCImplementation:
3335 case Decl::ObjCInterface:
3336 case Decl::ObjCIvar:
3337 case Decl::ObjCMethod:
3338 case Decl::ObjCProperty:
3339 case Decl::ObjCPropertyImpl:
3340 case Decl::ObjCProtocol:
3341 return CXLanguage_ObjC;
3342 case Decl::CXXConstructor:
3343 case Decl::CXXConversion:
3344 case Decl::CXXDestructor:
3345 case Decl::CXXMethod:
3346 case Decl::CXXRecord:
3347 case Decl::ClassTemplate:
3348 case Decl::ClassTemplatePartialSpecialization:
3349 case Decl::ClassTemplateSpecialization:
3350 case Decl::Friend:
3351 case Decl::FriendTemplate:
3352 case Decl::FunctionTemplate:
3353 case Decl::LinkageSpec:
3354 case Decl::Namespace:
3355 case Decl::NamespaceAlias:
3356 case Decl::NonTypeTemplateParm:
3357 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003358 case Decl::TemplateTemplateParm:
3359 case Decl::TemplateTypeParm:
3360 case Decl::UnresolvedUsingTypename:
3361 case Decl::UnresolvedUsingValue:
3362 case Decl::Using:
3363 case Decl::UsingDirective:
3364 case Decl::UsingShadow:
3365 return CXLanguage_CPlusPlus;
3366 }
3367
3368 return CXLanguage_C;
3369}
3370
3371extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003372
3373enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3374 if (clang_isDeclaration(cursor.kind))
3375 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3376 if (D->hasAttr<UnavailableAttr>() ||
3377 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3378 return CXAvailability_Available;
3379
3380 if (D->hasAttr<DeprecatedAttr>())
3381 return CXAvailability_Deprecated;
3382 }
3383
3384 return CXAvailability_Available;
3385}
3386
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003387CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3388 if (clang_isDeclaration(cursor.kind))
3389 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3390
3391 return CXLanguage_Invalid;
3392}
3393} // end: extern "C"
3394
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003395
3396//===----------------------------------------------------------------------===//
3397// C++ AST instrospection.
3398//===----------------------------------------------------------------------===//
3399
3400extern "C" {
3401unsigned clang_CXXMethod_isStatic(CXCursor C) {
3402 if (!clang_isDeclaration(C.kind))
3403 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003404
3405 CXXMethodDecl *Method = 0;
3406 Decl *D = cxcursor::getCursorDecl(C);
3407 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3408 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3409 else
3410 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3411 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003412}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003413
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003414} // end: extern "C"
3415
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003416//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003417// Attribute introspection.
3418//===----------------------------------------------------------------------===//
3419
3420extern "C" {
3421CXType clang_getIBOutletCollectionType(CXCursor C) {
3422 if (C.kind != CXCursor_IBOutletCollectionAttr)
3423 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3424
3425 IBOutletCollectionAttr *A =
3426 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3427
3428 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3429}
3430} // end: extern "C"
3431
3432//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003433// CXString Operations.
3434//===----------------------------------------------------------------------===//
3435
3436extern "C" {
3437const char *clang_getCString(CXString string) {
3438 return string.Spelling;
3439}
3440
3441void clang_disposeString(CXString string) {
3442 if (string.MustFreeString && string.Spelling)
3443 free((void*)string.Spelling);
3444}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003445
Ted Kremenekfb480492010-01-13 21:46:36 +00003446} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003447
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003448namespace clang { namespace cxstring {
3449CXString createCXString(const char *String, bool DupString){
3450 CXString Str;
3451 if (DupString) {
3452 Str.Spelling = strdup(String);
3453 Str.MustFreeString = 1;
3454 } else {
3455 Str.Spelling = String;
3456 Str.MustFreeString = 0;
3457 }
3458 return Str;
3459}
3460
3461CXString createCXString(llvm::StringRef String, bool DupString) {
3462 CXString Result;
3463 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3464 char *Spelling = (char *)malloc(String.size() + 1);
3465 memmove(Spelling, String.data(), String.size());
3466 Spelling[String.size()] = 0;
3467 Result.Spelling = Spelling;
3468 Result.MustFreeString = 1;
3469 } else {
3470 Result.Spelling = String.data();
3471 Result.MustFreeString = 0;
3472 }
3473 return Result;
3474}
3475}}
3476
Ted Kremenek04bb7162010-01-22 22:44:15 +00003477//===----------------------------------------------------------------------===//
3478// Misc. utility functions.
3479//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003480
Ted Kremenek04bb7162010-01-22 22:44:15 +00003481extern "C" {
3482
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003483CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003484 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003485}
3486
3487} // end: extern "C"