blob: 947b3b2826264ffb050eb724e514290d93618397 [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);
Douglas Gregor7e242562010-09-01 19:52:22 +0000322 bool VisitUsingDecl(UsingDecl *D);
323 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
324 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000325
Douglas Gregor01829d32010-08-31 14:41:23 +0000326 // Name visitor
327 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
328
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000329 // Template visitors
330 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000331 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000332 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
333
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000334 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000335 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000336 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000337 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000338 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
339 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000340 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000341 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000342 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000343 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
344 bool VisitPointerTypeLoc(PointerTypeLoc TL);
345 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
346 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
347 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
348 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000349 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000350 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000351 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000352 // FIXME: Implement visitors here when the unimplemented TypeLocs get
353 // implemented
354 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
355 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000356
Douglas Gregora59e3902010-01-21 23:27:09 +0000357 // Statement visitors
358 bool VisitStmt(Stmt *S);
359 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000360 // FIXME: LabelStmt label?
361 bool VisitIfStmt(IfStmt *S);
362 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000363 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000364 bool VisitWhileStmt(WhileStmt *S);
365 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000366// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000367
Douglas Gregor336fd812010-01-23 00:40:08 +0000368 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000369 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
370 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000371 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000372 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000373 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000374 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000375 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000376 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000377 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000378 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000379 // FIXME: AddrLabelExpr (once we have cursors for labels)
380 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
381 bool VisitVAArgExpr(VAArgExpr *E);
382 // FIXME: InitListExpr (for the designators)
383 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000384};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000385
Ted Kremenekab188932010-01-05 19:32:54 +0000386} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000387
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000388static SourceRange getRawCursorExtent(CXCursor C);
389
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000390RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000391 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
392}
393
Douglas Gregorb1373d02010-01-20 20:59:29 +0000394/// \brief Visit the given cursor and, if requested by the visitor,
395/// its children.
396///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000397/// \param Cursor the cursor to visit.
398///
399/// \param CheckRegionOfInterest if true, then the caller already checked that
400/// this cursor is within the region of interest.
401///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000402/// \returns true if the visitation should be aborted, false if it
403/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000404bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405 if (clang_isInvalid(Cursor.kind))
406 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000407
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408 if (clang_isDeclaration(Cursor.kind)) {
409 Decl *D = getCursorDecl(Cursor);
410 assert(D && "Invalid declaration cursor");
411 if (D->getPCHLevel() > MaxPCHLevel)
412 return false;
413
414 if (D->isImplicit())
415 return false;
416 }
417
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000418 // If we have a range of interest, and this cursor doesn't intersect with it,
419 // we're done.
420 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000421 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000422 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000423 return false;
424 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000425
Douglas Gregorb1373d02010-01-20 20:59:29 +0000426 switch (Visitor(Cursor, Parent, ClientData)) {
427 case CXChildVisit_Break:
428 return true;
429
430 case CXChildVisit_Continue:
431 return false;
432
433 case CXChildVisit_Recurse:
434 return VisitChildren(Cursor);
435 }
436
Douglas Gregorfd643772010-01-25 16:45:46 +0000437 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000438}
439
Douglas Gregor788f5a12010-03-20 00:41:21 +0000440std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
441CursorVisitor::getPreprocessedEntities() {
442 PreprocessingRecord &PPRec
443 = *TU->getPreprocessor().getPreprocessingRecord();
444
445 bool OnlyLocalDecls
446 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
447
448 // There is no region of interest; we have to walk everything.
449 if (RegionOfInterest.isInvalid())
450 return std::make_pair(PPRec.begin(OnlyLocalDecls),
451 PPRec.end(OnlyLocalDecls));
452
453 // Find the file in which the region of interest lands.
454 SourceManager &SM = TU->getSourceManager();
455 std::pair<FileID, unsigned> Begin
456 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
457 std::pair<FileID, unsigned> End
458 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
459
460 // The region of interest spans files; we have to walk everything.
461 if (Begin.first != End.first)
462 return std::make_pair(PPRec.begin(OnlyLocalDecls),
463 PPRec.end(OnlyLocalDecls));
464
465 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
466 = TU->getPreprocessedEntitiesByFile();
467 if (ByFileMap.empty()) {
468 // Build the mapping from files to sets of preprocessed entities.
469 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
470 EEnd = PPRec.end(OnlyLocalDecls);
471 E != EEnd; ++E) {
472 std::pair<FileID, unsigned> P
473 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
474 ByFileMap[P.first].push_back(*E);
475 }
476 }
477
478 return std::make_pair(ByFileMap[Begin.first].begin(),
479 ByFileMap[Begin.first].end());
480}
481
Douglas Gregorb1373d02010-01-20 20:59:29 +0000482/// \brief Visit the children of the given cursor.
483///
484/// \returns true if the visitation should be aborted, false if it
485/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000486bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000487 if (clang_isReference(Cursor.kind)) {
488 // By definition, references have no children.
489 return false;
490 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000491
492 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000493 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000494 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000495
Douglas Gregorb1373d02010-01-20 20:59:29 +0000496 if (clang_isDeclaration(Cursor.kind)) {
497 Decl *D = getCursorDecl(Cursor);
498 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000499 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000500 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000501
Douglas Gregora59e3902010-01-21 23:27:09 +0000502 if (clang_isStatement(Cursor.kind))
503 return Visit(getCursorStmt(Cursor));
504 if (clang_isExpression(Cursor.kind))
505 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000506
Douglas Gregorb1373d02010-01-20 20:59:29 +0000507 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000508 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000509 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
510 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000511 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
512 TLEnd = CXXUnit->top_level_end();
513 TL != TLEnd; ++TL) {
514 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000515 return true;
516 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000517 } else if (VisitDeclContext(
518 CXXUnit->getASTContext().getTranslationUnitDecl()))
519 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000520
Douglas Gregor0396f462010-03-19 05:22:59 +0000521 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000522 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000523 // FIXME: Once we have the ability to deserialize a preprocessing record,
524 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000525 PreprocessingRecord::iterator E, EEnd;
526 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000527 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
528 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
529 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000530
Douglas Gregor0396f462010-03-19 05:22:59 +0000531 continue;
532 }
533
534 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
535 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
536 return true;
537
538 continue;
539 }
540 }
541 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000542 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000543 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000544
Douglas Gregorb1373d02010-01-20 20:59:29 +0000545 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000546 return false;
547}
548
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000549bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000550 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
551 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000552
Ted Kremenek664cffd2010-07-22 11:30:19 +0000553 if (Stmt *Body = B->getBody())
554 return Visit(MakeCXCursor(Body, StmtParent, TU));
555
556 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000557}
558
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000560 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000561 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000562
Ted Kremenek23173d72010-05-18 21:09:07 +0000563 Decl *D = *I;
564 if (D->getLexicalDeclContext() != DC)
565 continue;
566
567 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000568
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000569 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000570 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000571 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000572 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000573
574 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000575 case RangeBefore:
576 // This declaration comes before the region of interest; skip it.
577 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000578
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000579 case RangeAfter:
580 // This declaration comes after the region of interest; we're done.
581 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000582
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000583 case RangeOverlap:
584 // This declaration overlaps the region of interest; visit it.
585 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000586 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000587 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000588
Daniel Dunbard52864b2010-02-14 10:02:57 +0000589 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000590 return true;
591 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000592
Douglas Gregorb1373d02010-01-20 20:59:29 +0000593 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000594}
595
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000596bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
597 llvm_unreachable("Translation units are visited directly by Visit()");
598 return false;
599}
600
601bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
602 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
603 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000604
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000605 return false;
606}
607
608bool CursorVisitor::VisitTagDecl(TagDecl *D) {
609 return VisitDeclContext(D);
610}
611
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000612bool CursorVisitor::VisitClassTemplateSpecializationDecl(
613 ClassTemplateSpecializationDecl *D) {
614 bool ShouldVisitBody = false;
615 switch (D->getSpecializationKind()) {
616 case TSK_Undeclared:
617 case TSK_ImplicitInstantiation:
618 // Nothing to visit
619 return false;
620
621 case TSK_ExplicitInstantiationDeclaration:
622 case TSK_ExplicitInstantiationDefinition:
623 break;
624
625 case TSK_ExplicitSpecialization:
626 ShouldVisitBody = true;
627 break;
628 }
629
630 // Visit the template arguments used in the specialization.
631 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
632 TypeLoc TL = SpecType->getTypeLoc();
633 if (TemplateSpecializationTypeLoc *TSTLoc
634 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
635 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
636 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
637 return true;
638 }
639 }
640
641 if (ShouldVisitBody && VisitCXXRecordDecl(D))
642 return true;
643
644 return false;
645}
646
Douglas Gregor74dbe642010-08-31 19:31:58 +0000647bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
648 ClassTemplatePartialSpecializationDecl *D) {
649 // FIXME: Visit the "outer" template parameter lists on the TagDecl
650 // before visiting these template parameters.
651 if (VisitTemplateParameters(D->getTemplateParameters()))
652 return true;
653
654 // Visit the partial specialization arguments.
655 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
656 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
657 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
658 return true;
659
660 return VisitCXXRecordDecl(D);
661}
662
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000663bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
664 // FIXME: Visit default argument
665 return false;
666}
667
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000668bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
669 if (Expr *Init = D->getInitExpr())
670 return Visit(MakeCXCursor(Init, StmtParent, TU));
671 return false;
672}
673
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000674bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
675 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
676 if (Visit(TSInfo->getTypeLoc()))
677 return true;
678
679 return false;
680}
681
Douglas Gregorb1373d02010-01-20 20:59:29 +0000682bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000683 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
684 // Visit the function declaration's syntactic components in the order
685 // written. This requires a bit of work.
686 TypeLoc TL = TSInfo->getTypeLoc();
687 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
688
689 // If we have a function declared directly (without the use of a typedef),
690 // visit just the return type. Otherwise, just visit the function's type
691 // now.
692 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
693 (!FTL && Visit(TL)))
694 return true;
695
696 // FIXME: Visit the nested-name-specifier, if present.
697
698 // Visit the declaration name.
699 if (VisitDeclarationNameInfo(ND->getNameInfo()))
700 return true;
701
702 // FIXME: Visit explicitly-specified template arguments!
703
704 // Visit the function parameters, if we have a function type.
705 if (FTL && VisitFunctionTypeLoc(*FTL, true))
706 return true;
707
708 // FIXME: Attributes?
709 }
710
Douglas Gregora59e3902010-01-21 23:27:09 +0000711 if (ND->isThisDeclarationADefinition() &&
712 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
713 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000714
Douglas Gregorb1373d02010-01-20 20:59:29 +0000715 return false;
716}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000717
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000718bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
719 if (VisitDeclaratorDecl(D))
720 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000721
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000722 if (Expr *BitWidth = D->getBitWidth())
723 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000724
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000725 return false;
726}
727
728bool CursorVisitor::VisitVarDecl(VarDecl *D) {
729 if (VisitDeclaratorDecl(D))
730 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000731
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000732 if (Expr *Init = D->getInit())
733 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000734
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000735 return false;
736}
737
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000738bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
739 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
740 // before visiting these template parameters.
741 if (VisitTemplateParameters(D->getTemplateParameters()))
742 return true;
743
744 return VisitFunctionDecl(D->getTemplatedDecl());
745}
746
Douglas Gregor39d6f072010-08-31 19:02:00 +0000747bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
748 // FIXME: Visit the "outer" template parameter lists on the TagDecl
749 // before visiting these template parameters.
750 if (VisitTemplateParameters(D->getTemplateParameters()))
751 return true;
752
753 return VisitCXXRecordDecl(D->getTemplatedDecl());
754}
755
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000756bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000757 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
758 if (Visit(TSInfo->getTypeLoc()))
759 return true;
760
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000761 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000762 PEnd = ND->param_end();
763 P != PEnd; ++P) {
764 if (Visit(MakeCXCursor(*P, TU)))
765 return true;
766 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000767
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000768 if (ND->isThisDeclarationADefinition() &&
769 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
770 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000771
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000772 return false;
773}
774
Douglas Gregora59e3902010-01-21 23:27:09 +0000775bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
776 return VisitDeclContext(D);
777}
778
Douglas Gregorb1373d02010-01-20 20:59:29 +0000779bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000780 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
781 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000782 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000783
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000784 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
785 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
786 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000787 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000788 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000789
Douglas Gregora59e3902010-01-21 23:27:09 +0000790 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000791}
792
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000793bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
794 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
795 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
796 E = PID->protocol_end(); I != E; ++I, ++PL)
797 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
798 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000799
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000800 return VisitObjCContainerDecl(PID);
801}
802
Ted Kremenek23173d72010-05-18 21:09:07 +0000803bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000804 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
805 return true;
806
Ted Kremenek23173d72010-05-18 21:09:07 +0000807 // FIXME: This implements a workaround with @property declarations also being
808 // installed in the DeclContext for the @interface. Eventually this code
809 // should be removed.
810 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
811 if (!CDecl || !CDecl->IsClassExtension())
812 return false;
813
814 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
815 if (!ID)
816 return false;
817
818 IdentifierInfo *PropertyId = PD->getIdentifier();
819 ObjCPropertyDecl *prevDecl =
820 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
821
822 if (!prevDecl)
823 return false;
824
825 // Visit synthesized methods since they will be skipped when visiting
826 // the @interface.
827 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
828 if (MD->isSynthesized())
829 if (Visit(MakeCXCursor(MD, TU)))
830 return true;
831
832 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
833 if (MD->isSynthesized())
834 if (Visit(MakeCXCursor(MD, TU)))
835 return true;
836
837 return false;
838}
839
Douglas Gregorb1373d02010-01-20 20:59:29 +0000840bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000841 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000842 if (D->getSuperClass() &&
843 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000844 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000845 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000846 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000847
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000848 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
849 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
850 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000851 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000852 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000853
Douglas Gregora59e3902010-01-21 23:27:09 +0000854 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000855}
856
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000857bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
858 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000859}
860
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000861bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000862 // 'ID' could be null when dealing with invalid code.
863 if (ObjCInterfaceDecl *ID = D->getClassInterface())
864 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
865 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000866
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000867 return VisitObjCImplDecl(D);
868}
869
870bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
871#if 0
872 // Issue callbacks for super class.
873 // FIXME: No source location information!
874 if (D->getSuperClass() &&
875 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000876 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000877 TU)))
878 return true;
879#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000880
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000881 return VisitObjCImplDecl(D);
882}
883
884bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
885 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
886 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
887 E = D->protocol_end();
888 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000889 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000890 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000891
892 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000893}
894
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000895bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
896 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
897 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
898 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000899
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000900 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000901}
902
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000903bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
904 return VisitDeclContext(D);
905}
906
Douglas Gregor69319002010-08-31 23:48:11 +0000907bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregor7e242562010-09-01 19:52:22 +0000908 // FIXME: Visit nested-name-specifier.
Douglas Gregor69319002010-08-31 23:48:11 +0000909
910 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
911 D->getTargetNameLoc(), TU));
912}
913
Douglas Gregor7e242562010-09-01 19:52:22 +0000914bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
915 // FIXME: Visit nested-name-specifier.
916
917 // FIXME: Provide a multi-reference of some kind for all of the declarations
918 // that the using declaration refers to. We don't have this kind of cursor
919 // yet.
920
921 return VisitDeclarationNameInfo(D->getNameInfo());
922}
923
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000924bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor7e242562010-09-01 19:52:22 +0000925 // FIXME: Visit nested-name-specifier.
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000926
927 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
928 D->getIdentLocation(), TU));
929}
930
Douglas Gregor7e242562010-09-01 19:52:22 +0000931bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
932 // FIXME: Visit nested-name-specifier.
933
934 return VisitDeclarationNameInfo(D->getNameInfo());
935}
936
937bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
938 UnresolvedUsingTypenameDecl *D) {
939 // FIXME: Visit nested-name-specifier.
940 return false;
941}
942
Douglas Gregor01829d32010-08-31 14:41:23 +0000943bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
944 switch (Name.getName().getNameKind()) {
945 case clang::DeclarationName::Identifier:
946 case clang::DeclarationName::CXXLiteralOperatorName:
947 case clang::DeclarationName::CXXOperatorName:
948 case clang::DeclarationName::CXXUsingDirective:
949 return false;
950
951 case clang::DeclarationName::CXXConstructorName:
952 case clang::DeclarationName::CXXDestructorName:
953 case clang::DeclarationName::CXXConversionFunctionName:
954 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
955 return Visit(TSInfo->getTypeLoc());
956 return false;
957
958 case clang::DeclarationName::ObjCZeroArgSelector:
959 case clang::DeclarationName::ObjCOneArgSelector:
960 case clang::DeclarationName::ObjCMultiArgSelector:
961 // FIXME: Per-identifier location info?
962 return false;
963 }
964
965 return false;
966}
967
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000968bool CursorVisitor::VisitTemplateParameters(
969 const TemplateParameterList *Params) {
970 if (!Params)
971 return false;
972
973 for (TemplateParameterList::const_iterator P = Params->begin(),
974 PEnd = Params->end();
975 P != PEnd; ++P) {
976 if (Visit(MakeCXCursor(*P, TU)))
977 return true;
978 }
979
980 return false;
981}
982
Douglas Gregor0b36e612010-08-31 20:37:03 +0000983bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
984 switch (Name.getKind()) {
985 case TemplateName::Template:
986 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
987
988 case TemplateName::OverloadedTemplate:
989 // FIXME: We need a way to return multiple lookup results in a single
990 // cursor.
991 return false;
992
993 case TemplateName::DependentTemplate:
994 // FIXME: Visit nested-name-specifier.
995 return false;
996
997 case TemplateName::QualifiedTemplate:
998 // FIXME: Visit nested-name-specifier.
999 return Visit(MakeCursorTemplateRef(
1000 Name.getAsQualifiedTemplateName()->getDecl(),
1001 Loc, TU));
1002 }
1003
1004 return false;
1005}
1006
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001007bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1008 switch (TAL.getArgument().getKind()) {
1009 case TemplateArgument::Null:
1010 case TemplateArgument::Integral:
1011 return false;
1012
1013 case TemplateArgument::Pack:
1014 // FIXME: Implement when variadic templates come along.
1015 return false;
1016
1017 case TemplateArgument::Type:
1018 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1019 return Visit(TSInfo->getTypeLoc());
1020 return false;
1021
1022 case TemplateArgument::Declaration:
1023 if (Expr *E = TAL.getSourceDeclExpression())
1024 return Visit(MakeCXCursor(E, StmtParent, TU));
1025 return false;
1026
1027 case TemplateArgument::Expression:
1028 if (Expr *E = TAL.getSourceExpression())
1029 return Visit(MakeCXCursor(E, StmtParent, TU));
1030 return false;
1031
1032 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001033 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1034 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001035 }
1036
1037 return false;
1038}
1039
Ted Kremeneka0536d82010-05-07 01:04:29 +00001040bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1041 return VisitDeclContext(D);
1042}
1043
Douglas Gregor01829d32010-08-31 14:41:23 +00001044bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1045 return Visit(TL.getUnqualifiedLoc());
1046}
1047
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001048bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1049 ASTContext &Context = TU->getASTContext();
1050
1051 // Some builtin types (such as Objective-C's "id", "sel", and
1052 // "Class") have associated declarations. Create cursors for those.
1053 QualType VisitType;
1054 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001055 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001056 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001057 case BuiltinType::Char_U:
1058 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001059 case BuiltinType::Char16:
1060 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001061 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001062 case BuiltinType::UInt:
1063 case BuiltinType::ULong:
1064 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001065 case BuiltinType::UInt128:
1066 case BuiltinType::Char_S:
1067 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001068 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001069 case BuiltinType::Short:
1070 case BuiltinType::Int:
1071 case BuiltinType::Long:
1072 case BuiltinType::LongLong:
1073 case BuiltinType::Int128:
1074 case BuiltinType::Float:
1075 case BuiltinType::Double:
1076 case BuiltinType::LongDouble:
1077 case BuiltinType::NullPtr:
1078 case BuiltinType::Overload:
1079 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001080 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001081
1082 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001083 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001084
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001085 case BuiltinType::ObjCId:
1086 VisitType = Context.getObjCIdType();
1087 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001088
1089 case BuiltinType::ObjCClass:
1090 VisitType = Context.getObjCClassType();
1091 break;
1092
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001093 case BuiltinType::ObjCSel:
1094 VisitType = Context.getObjCSelType();
1095 break;
1096 }
1097
1098 if (!VisitType.isNull()) {
1099 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001100 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001101 TU));
1102 }
1103
1104 return false;
1105}
1106
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001107bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1108 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1109}
1110
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001111bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1112 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1113}
1114
1115bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1116 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1117}
1118
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001119bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1120 // FIXME: We can't visit the template template parameter, but there's
1121 // no context information with which we can match up the depth/index in the
1122 // type to the appropriate
1123 return false;
1124}
1125
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001126bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1127 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1128 return true;
1129
John McCallc12c5bb2010-05-15 11:32:37 +00001130 return false;
1131}
1132
1133bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1134 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1135 return true;
1136
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001137 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1138 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1139 TU)))
1140 return true;
1141 }
1142
1143 return false;
1144}
1145
1146bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001147 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001148}
1149
1150bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1151 return Visit(TL.getPointeeLoc());
1152}
1153
1154bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1155 return Visit(TL.getPointeeLoc());
1156}
1157
1158bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1159 return Visit(TL.getPointeeLoc());
1160}
1161
1162bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001163 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001164}
1165
1166bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001167 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001168}
1169
Douglas Gregor01829d32010-08-31 14:41:23 +00001170bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1171 bool SkipResultType) {
1172 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001173 return true;
1174
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001175 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001176 if (Decl *D = TL.getArg(I))
1177 if (Visit(MakeCXCursor(D, TU)))
1178 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001179
1180 return false;
1181}
1182
1183bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1184 if (Visit(TL.getElementLoc()))
1185 return true;
1186
1187 if (Expr *Size = TL.getSizeExpr())
1188 return Visit(MakeCXCursor(Size, StmtParent, TU));
1189
1190 return false;
1191}
1192
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001193bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1194 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001195 // Visit the template name.
1196 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1197 TL.getTemplateNameLoc()))
1198 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001199
1200 // Visit the template arguments.
1201 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1202 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1203 return true;
1204
1205 return false;
1206}
1207
Douglas Gregor2332c112010-01-21 20:48:56 +00001208bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1209 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1210}
1211
1212bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1213 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1214 return Visit(TSInfo->getTypeLoc());
1215
1216 return false;
1217}
1218
Douglas Gregora59e3902010-01-21 23:27:09 +00001219bool CursorVisitor::VisitStmt(Stmt *S) {
1220 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1221 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001222 if (Stmt *C = *Child)
1223 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1224 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001225 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001226
Douglas Gregora59e3902010-01-21 23:27:09 +00001227 return false;
1228}
1229
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001230bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1231 // Specially handle CaseStmts because they can be nested, e.g.:
1232 //
1233 // case 1:
1234 // case 2:
1235 //
1236 // In this case the second CaseStmt is the child of the first. Walking
1237 // these recursively can blow out the stack.
1238 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1239 while (true) {
1240 // Set the Parent field to Cursor, then back to its old value once we're
1241 // done.
1242 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1243
1244 if (Stmt *LHS = S->getLHS())
1245 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1246 return true;
1247 if (Stmt *RHS = S->getRHS())
1248 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1249 return true;
1250 if (Stmt *SubStmt = S->getSubStmt()) {
1251 if (!isa<CaseStmt>(SubStmt))
1252 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1253
1254 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1255 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1256 Cursor = MakeCXCursor(CS, StmtParent, TU);
1257 if (RegionOfInterest.isValid()) {
1258 SourceRange Range = CS->getSourceRange();
1259 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1260 return false;
1261 }
1262
1263 switch (Visitor(Cursor, Parent, ClientData)) {
1264 case CXChildVisit_Break: return true;
1265 case CXChildVisit_Continue: return false;
1266 case CXChildVisit_Recurse:
1267 // Perform tail-recursion manually.
1268 S = CS;
1269 continue;
1270 }
1271 }
1272 return false;
1273 }
1274}
1275
Douglas Gregora59e3902010-01-21 23:27:09 +00001276bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1277 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1278 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001279 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001280 return true;
1281 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001282
Douglas Gregora59e3902010-01-21 23:27:09 +00001283 return false;
1284}
1285
Douglas Gregorf5bab412010-01-22 01:00:11 +00001286bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1287 if (VarDecl *Var = S->getConditionVariable()) {
1288 if (Visit(MakeCXCursor(Var, TU)))
1289 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001290 }
1291
Douglas Gregor263b47b2010-01-25 16:12:32 +00001292 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1293 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001294 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1295 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001296 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1297 return true;
1298
1299 return false;
1300}
1301
1302bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1303 if (VarDecl *Var = S->getConditionVariable()) {
1304 if (Visit(MakeCXCursor(Var, TU)))
1305 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001306 }
1307
Douglas Gregor263b47b2010-01-25 16:12:32 +00001308 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1309 return true;
1310 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1311 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001312
Douglas Gregor263b47b2010-01-25 16:12:32 +00001313 return false;
1314}
1315
1316bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1317 if (VarDecl *Var = S->getConditionVariable()) {
1318 if (Visit(MakeCXCursor(Var, TU)))
1319 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001320 }
1321
Douglas Gregor263b47b2010-01-25 16:12:32 +00001322 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1323 return true;
1324 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001325 return true;
1326
Douglas Gregor263b47b2010-01-25 16:12:32 +00001327 return false;
1328}
1329
1330bool CursorVisitor::VisitForStmt(ForStmt *S) {
1331 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1332 return true;
1333 if (VarDecl *Var = S->getConditionVariable()) {
1334 if (Visit(MakeCXCursor(Var, TU)))
1335 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001336 }
1337
Douglas Gregor263b47b2010-01-25 16:12:32 +00001338 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1339 return true;
1340 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1341 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001342 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1343 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001344
Douglas Gregorf5bab412010-01-22 01:00:11 +00001345 return false;
1346}
1347
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001348bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1349 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1350 return true;
1351
1352 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1353 return true;
1354
1355 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1356 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1357 return true;
1358
1359 return false;
1360}
1361
Ted Kremenek3064ef92010-08-27 21:34:58 +00001362bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1363 if (D->isDefinition()) {
1364 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1365 E = D->bases_end(); I != E; ++I) {
1366 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1367 return true;
1368 }
1369 }
1370
1371 return VisitTagDecl(D);
1372}
1373
1374
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001375bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1376 return Visit(B->getBlockDecl());
1377}
1378
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001379bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1380 // FIXME: Visit fields as well?
1381 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1382 return true;
1383
1384 return VisitExpr(E);
1385}
1386
Douglas Gregor336fd812010-01-23 00:40:08 +00001387bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1388 if (E->isArgumentType()) {
1389 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1390 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001391
Douglas Gregor336fd812010-01-23 00:40:08 +00001392 return false;
1393 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001394
Douglas Gregor336fd812010-01-23 00:40:08 +00001395 return VisitExpr(E);
1396}
1397
1398bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1399 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1400 if (Visit(TSInfo->getTypeLoc()))
1401 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001402
Douglas Gregor336fd812010-01-23 00:40:08 +00001403 return VisitCastExpr(E);
1404}
1405
1406bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1407 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1408 if (Visit(TSInfo->getTypeLoc()))
1409 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001410
Douglas Gregor336fd812010-01-23 00:40:08 +00001411 return VisitExpr(E);
1412}
1413
Douglas Gregor648220e2010-08-10 15:02:34 +00001414bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1415 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1416 Visit(E->getArgTInfo2()->getTypeLoc());
1417}
1418
1419bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1420 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1421 return true;
1422
1423 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1424}
1425
Douglas Gregorc2350e52010-03-08 16:40:19 +00001426bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001427 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1428 if (Visit(TSInfo->getTypeLoc()))
1429 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001430
1431 return VisitExpr(E);
1432}
1433
Douglas Gregor81d34662010-04-20 15:39:42 +00001434bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1435 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1436}
1437
1438
Ted Kremenek09dfa372010-02-18 05:46:33 +00001439bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001440 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1441 i != e; ++i)
1442 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001443 return true;
1444
1445 return false;
1446}
1447
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001448extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001449CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1450 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001451 // We use crash recovery to make some of our APIs more reliable, implicitly
1452 // enable it.
1453 llvm::CrashRecoveryContext::Enable();
1454
Douglas Gregora030b7c2010-01-22 20:35:53 +00001455 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001456 if (excludeDeclarationsFromPCH)
1457 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001458 if (displayDiagnostics)
1459 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001460 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001461}
1462
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001463void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001464 if (CIdx)
1465 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001466 if (getenv("LIBCLANG_TIMING"))
1467 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001468}
1469
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001470void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001471 if (CIdx) {
1472 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1473 CXXIdx->setUseExternalASTGeneration(value);
1474 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001475}
1476
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001477CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001478 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001479 if (!CIdx)
1480 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001481
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001482 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001483
Douglas Gregor28019772010-04-05 23:52:57 +00001484 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001485 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001486 CXXIdx->getOnlyLocalDecls(),
1487 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001488}
1489
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001490unsigned clang_defaultEditingTranslationUnitOptions() {
1491 return CXTranslationUnit_PrecompiledPreamble;
1492}
1493
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001494CXTranslationUnit
1495clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1496 const char *source_filename,
1497 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001498 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001499 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001500 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001501 return clang_parseTranslationUnit(CIdx, source_filename,
1502 command_line_args, num_command_line_args,
1503 unsaved_files, num_unsaved_files,
1504 CXTranslationUnit_DetailedPreprocessingRecord);
1505}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001506
1507struct ParseTranslationUnitInfo {
1508 CXIndex CIdx;
1509 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001510 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001511 int num_command_line_args;
1512 struct CXUnsavedFile *unsaved_files;
1513 unsigned num_unsaved_files;
1514 unsigned options;
1515 CXTranslationUnit result;
1516};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001517static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001518 ParseTranslationUnitInfo *PTUI =
1519 static_cast<ParseTranslationUnitInfo*>(UserData);
1520 CXIndex CIdx = PTUI->CIdx;
1521 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001522 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001523 int num_command_line_args = PTUI->num_command_line_args;
1524 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1525 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1526 unsigned options = PTUI->options;
1527 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001528
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001529 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001530 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001531
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001532 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1533
Douglas Gregor44c181a2010-07-23 00:33:23 +00001534 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001535 bool CompleteTranslationUnit
1536 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001537 bool CacheCodeCompetionResults
1538 = options & CXTranslationUnit_CacheCompletionResults;
1539
Douglas Gregor5352ac02010-01-28 00:27:43 +00001540 // Configure the diagnostics.
1541 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001542 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1543 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001544
Douglas Gregor4db64a42010-01-23 00:14:00 +00001545 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1546 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001547 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001548 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001549 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001550 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1551 Buffer));
1552 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001553
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001554 if (!CXXIdx->getUseExternalASTGeneration()) {
1555 llvm::SmallVector<const char *, 16> Args;
1556
1557 // The 'source_filename' argument is optional. If the caller does not
1558 // specify it then it is assumed that the source file is specified
1559 // in the actual argument list.
1560 if (source_filename)
1561 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001562
1563 // Since the Clang C library is primarily used by batch tools dealing with
1564 // (often very broken) source code, where spell-checking can have a
1565 // significant negative impact on performance (particularly when
1566 // precompiled headers are involved), we disable it by default.
1567 // Note that we place this argument early in the list, so that it can be
1568 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001569 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001570
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001571 Args.insert(Args.end(), command_line_args,
1572 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001573
Douglas Gregor44c181a2010-07-23 00:33:23 +00001574 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001575 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1576 Args.push_back("-Xclang");
1577 Args.push_back("-detailed-preprocessing-record");
1578 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001579
Douglas Gregor5352ac02010-01-28 00:27:43 +00001580 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001581
Ted Kremenek29b72842010-01-07 22:49:05 +00001582#ifdef USE_CRASHTRACER
1583 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001584#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001585
Daniel Dunbar94220972009-12-05 02:17:18 +00001586 llvm::OwningPtr<ASTUnit> Unit(
1587 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001588 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001589 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001590 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001591 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001592 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001593 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001594 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001595 CompleteTranslationUnit,
1596 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001597
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001598 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001599 // Make sure to check that 'Unit' is non-NULL.
1600 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001601 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1602 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001603 D != DEnd; ++D) {
1604 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001605 CXString Msg = clang_formatDiagnostic(&Diag,
1606 clang_defaultDiagnosticDisplayOptions());
1607 fprintf(stderr, "%s\n", clang_getCString(Msg));
1608 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001609 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001610#ifdef LLVM_ON_WIN32
1611 // On Windows, force a flush, since there may be multiple copies of
1612 // stderr and stdout in the file system, all with different buffers
1613 // but writing to the same device.
1614 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001615#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001616 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001617 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001618
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001619 PTUI->result = Unit.take();
1620 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001621 }
1622
Ted Kremenek139ba862009-10-22 00:03:57 +00001623 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001624 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001625
Ted Kremenek139ba862009-10-22 00:03:57 +00001626 // First add the complete path to the 'clang' executable.
1627 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001628 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001629
Ted Kremenek139ba862009-10-22 00:03:57 +00001630 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001631 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001632
Ted Kremenek139ba862009-10-22 00:03:57 +00001633 // The 'source_filename' argument is optional. If the caller does not
1634 // specify it then it is assumed that the source file is specified
1635 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001636 if (source_filename)
1637 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001638
Steve Naroff37b5ac22009-10-15 20:50:09 +00001639 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001640 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001641 char astTmpFile[L_tmpnam];
1642 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001643
1644 // Since the Clang C library is primarily used by batch tools dealing with
1645 // (often very broken) source code, where spell-checking can have a
1646 // significant negative impact on performance (particularly when
1647 // precompiled headers are involved), we disable it by default.
1648 // Note that we place this argument early in the list, so that it can be
1649 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001650 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001651
Douglas Gregor4db64a42010-01-23 00:14:00 +00001652 // Remap any unsaved files to temporary files.
1653 std::vector<llvm::sys::Path> TemporaryFiles;
1654 std::vector<std::string> RemapArgs;
1655 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001656 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001657
Douglas Gregor4db64a42010-01-23 00:14:00 +00001658 // The pointers into the elements of RemapArgs are stable because we
1659 // won't be adding anything to RemapArgs after this point.
1660 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1661 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001662
Ted Kremenek139ba862009-10-22 00:03:57 +00001663 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1664 for (int i = 0; i < num_command_line_args; ++i)
1665 if (const char *arg = command_line_args[i]) {
1666 if (strcmp(arg, "-o") == 0) {
1667 ++i; // Also skip the matching argument.
1668 continue;
1669 }
1670 if (strcmp(arg, "-emit-ast") == 0 ||
1671 strcmp(arg, "-c") == 0 ||
1672 strcmp(arg, "-fsyntax-only") == 0) {
1673 continue;
1674 }
1675
1676 // Keep the argument.
1677 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001678 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001679
Douglas Gregord93256e2010-01-28 06:00:51 +00001680 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001681 char tmpFileResults[L_tmpnam];
1682 char *tmpResultsFileName = tmpnam(tmpFileResults);
1683 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001684 TemporaryFiles.push_back(DiagnosticsFile);
1685 argv.push_back("-fdiagnostics-binary");
1686
Douglas Gregor44c181a2010-07-23 00:33:23 +00001687 // Do we need the detailed preprocessing record?
1688 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1689 argv.push_back("-Xclang");
1690 argv.push_back("-detailed-preprocessing-record");
1691 }
1692
Ted Kremenek139ba862009-10-22 00:03:57 +00001693 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001694 argv.push_back(NULL);
1695
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001696 // Invoke 'clang'.
1697 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1698 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001699 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001700 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1701 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001702 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001703 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001704 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001705
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001706 if (!ErrMsg.empty()) {
1707 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001708 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001709 I != E; ++I) {
1710 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001711 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001712 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001713 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001714
Daniel Dunbar32141c82010-02-23 20:23:45 +00001715 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001716 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001717
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001718 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001719 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001720 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001721 RemappedFiles.size(),
1722 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001723 if (ATU) {
1724 LoadSerializedDiagnostics(DiagnosticsFile,
1725 num_unsaved_files, unsaved_files,
1726 ATU->getFileManager(),
1727 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001728 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001729 } else if (CXXIdx->getDisplayDiagnostics()) {
1730 // We failed to load the ASTUnit, but we can still deserialize the
1731 // diagnostics and emit them.
1732 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001733 Diagnostic Diag;
1734 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001735 // FIXME: Faked LangOpts!
1736 LangOptions LangOpts;
1737 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1738 LoadSerializedDiagnostics(DiagnosticsFile,
1739 num_unsaved_files, unsaved_files,
1740 FileMgr, SourceMgr, Diags);
1741 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1742 DEnd = Diags.end();
1743 D != DEnd; ++D) {
1744 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001745 CXString Msg = clang_formatDiagnostic(&Diag,
1746 clang_defaultDiagnosticDisplayOptions());
1747 fprintf(stderr, "%s\n", clang_getCString(Msg));
1748 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001749 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001750
1751#ifdef LLVM_ON_WIN32
1752 // On Windows, force a flush, since there may be multiple copies of
1753 // stderr and stdout in the file system, all with different buffers
1754 // but writing to the same device.
1755 fflush(stderr);
1756#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001757 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001758
Douglas Gregor313e26c2010-02-18 23:35:40 +00001759 if (ATU) {
1760 // Make the translation unit responsible for destroying all temporary files.
1761 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1762 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001763 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001764 } else {
1765 // Destroy all of the temporary files now; they can't be referenced any
1766 // longer.
1767 llvm::sys::Path(astTmpFile).eraseFromDisk();
1768 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1769 TemporaryFiles[i].eraseFromDisk();
1770 }
1771
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001772 PTUI->result = ATU;
1773}
1774CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1775 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001776 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001777 int num_command_line_args,
1778 struct CXUnsavedFile *unsaved_files,
1779 unsigned num_unsaved_files,
1780 unsigned options) {
1781 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1782 num_command_line_args, unsaved_files, num_unsaved_files,
1783 options, 0 };
1784 llvm::CrashRecoveryContext CRC;
1785
1786 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001787 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1788 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1789 fprintf(stderr, " 'command_line_args' : [");
1790 for (int i = 0; i != num_command_line_args; ++i) {
1791 if (i)
1792 fprintf(stderr, ", ");
1793 fprintf(stderr, "'%s'", command_line_args[i]);
1794 }
1795 fprintf(stderr, "],\n");
1796 fprintf(stderr, " 'unsaved_files' : [");
1797 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1798 if (i)
1799 fprintf(stderr, ", ");
1800 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1801 unsaved_files[i].Length);
1802 }
1803 fprintf(stderr, "],\n");
1804 fprintf(stderr, " 'options' : %d,\n", options);
1805 fprintf(stderr, "}\n");
1806
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001807 return 0;
1808 }
1809
1810 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001811}
1812
Douglas Gregor19998442010-08-13 15:35:05 +00001813unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1814 return CXSaveTranslationUnit_None;
1815}
1816
1817int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1818 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001819 if (!TU)
1820 return 1;
1821
1822 return static_cast<ASTUnit *>(TU)->Save(FileName);
1823}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001824
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001825void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001826 if (CTUnit) {
1827 // If the translation unit has been marked as unsafe to free, just discard
1828 // it.
1829 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1830 return;
1831
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001832 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001833 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001834}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001835
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001836unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1837 return CXReparse_None;
1838}
1839
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001840struct ReparseTranslationUnitInfo {
1841 CXTranslationUnit TU;
1842 unsigned num_unsaved_files;
1843 struct CXUnsavedFile *unsaved_files;
1844 unsigned options;
1845 int result;
1846};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001847static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001848 ReparseTranslationUnitInfo *RTUI =
1849 static_cast<ReparseTranslationUnitInfo*>(UserData);
1850 CXTranslationUnit TU = RTUI->TU;
1851 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1852 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1853 unsigned options = RTUI->options;
1854 (void) options;
1855 RTUI->result = 1;
1856
Douglas Gregorabc563f2010-07-19 21:46:24 +00001857 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001858 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001859
1860 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1861 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1862 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1863 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001864 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001865 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1866 Buffer));
1867 }
1868
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001869 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1870 RemappedFiles.size()))
1871 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001872}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001873int clang_reparseTranslationUnit(CXTranslationUnit TU,
1874 unsigned num_unsaved_files,
1875 struct CXUnsavedFile *unsaved_files,
1876 unsigned options) {
1877 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1878 options, 0 };
1879 llvm::CrashRecoveryContext CRC;
1880
1881 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001882 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001883 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1884 return 1;
1885 }
1886
1887 return RTUI.result;
1888}
1889
Douglas Gregordf95a132010-08-09 20:45:32 +00001890
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001891CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001892 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001893 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001894
Steve Naroff77accc12009-09-03 18:19:54 +00001895 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001896 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001897}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001898
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001899CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001900 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001901 return Result;
1902}
1903
Ted Kremenekfb480492010-01-13 21:46:36 +00001904} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001905
Ted Kremenekfb480492010-01-13 21:46:36 +00001906//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001907// CXSourceLocation and CXSourceRange Operations.
1908//===----------------------------------------------------------------------===//
1909
Douglas Gregorb9790342010-01-22 21:44:22 +00001910extern "C" {
1911CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001912 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001913 return Result;
1914}
1915
1916unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001917 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1918 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1919 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001920}
1921
1922CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1923 CXFile file,
1924 unsigned line,
1925 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001926 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001927 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001928
Douglas Gregorb9790342010-01-22 21:44:22 +00001929 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1930 SourceLocation SLoc
1931 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001932 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001933 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001934
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001935 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001936}
1937
Douglas Gregor5352ac02010-01-28 00:27:43 +00001938CXSourceRange clang_getNullRange() {
1939 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1940 return Result;
1941}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001942
Douglas Gregor5352ac02010-01-28 00:27:43 +00001943CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1944 if (begin.ptr_data[0] != end.ptr_data[0] ||
1945 begin.ptr_data[1] != end.ptr_data[1])
1946 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001947
1948 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001949 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001950 return Result;
1951}
1952
Douglas Gregor46766dc2010-01-26 19:19:08 +00001953void clang_getInstantiationLocation(CXSourceLocation location,
1954 CXFile *file,
1955 unsigned *line,
1956 unsigned *column,
1957 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001958 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1959
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001960 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001961 if (file)
1962 *file = 0;
1963 if (line)
1964 *line = 0;
1965 if (column)
1966 *column = 0;
1967 if (offset)
1968 *offset = 0;
1969 return;
1970 }
1971
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001972 const SourceManager &SM =
1973 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001974 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001975
1976 if (file)
1977 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1978 if (line)
1979 *line = SM.getInstantiationLineNumber(InstLoc);
1980 if (column)
1981 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001982 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001983 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001984}
1985
Douglas Gregor1db19de2010-01-19 21:36:55 +00001986CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001987 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001988 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001989 return Result;
1990}
1991
1992CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001993 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001994 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001995 return Result;
1996}
1997
Douglas Gregorb9790342010-01-22 21:44:22 +00001998} // end: extern "C"
1999
Douglas Gregor1db19de2010-01-19 21:36:55 +00002000//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002001// CXFile Operations.
2002//===----------------------------------------------------------------------===//
2003
2004extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002005CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002006 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002007 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002008
Steve Naroff88145032009-10-27 14:35:18 +00002009 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002010 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002011}
2012
2013time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002014 if (!SFile)
2015 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002016
Steve Naroff88145032009-10-27 14:35:18 +00002017 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2018 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002019}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002020
Douglas Gregorb9790342010-01-22 21:44:22 +00002021CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2022 if (!tu)
2023 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002024
Douglas Gregorb9790342010-01-22 21:44:22 +00002025 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002026
Douglas Gregorb9790342010-01-22 21:44:22 +00002027 FileManager &FMgr = CXXUnit->getFileManager();
2028 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2029 return const_cast<FileEntry *>(File);
2030}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002031
Ted Kremenekfb480492010-01-13 21:46:36 +00002032} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002033
Ted Kremenekfb480492010-01-13 21:46:36 +00002034//===----------------------------------------------------------------------===//
2035// CXCursor Operations.
2036//===----------------------------------------------------------------------===//
2037
Ted Kremenekfb480492010-01-13 21:46:36 +00002038static Decl *getDeclFromExpr(Stmt *E) {
2039 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2040 return RefExpr->getDecl();
2041 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2042 return ME->getMemberDecl();
2043 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2044 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002045
Ted Kremenekfb480492010-01-13 21:46:36 +00002046 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2047 return getDeclFromExpr(CE->getCallee());
2048 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2049 return getDeclFromExpr(CE->getSubExpr());
2050 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2051 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002052
Ted Kremenekfb480492010-01-13 21:46:36 +00002053 return 0;
2054}
2055
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002056static SourceLocation getLocationFromExpr(Expr *E) {
2057 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2058 return /*FIXME:*/Msg->getLeftLoc();
2059 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2060 return DRE->getLocation();
2061 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2062 return Member->getMemberLoc();
2063 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2064 return Ivar->getLocation();
2065 return E->getLocStart();
2066}
2067
Ted Kremenekfb480492010-01-13 21:46:36 +00002068extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002069
2070unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002071 CXCursorVisitor visitor,
2072 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002073 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002074
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002075 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2076 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002077 return CursorVis.VisitChildren(parent);
2078}
2079
Douglas Gregor78205d42010-01-20 21:45:58 +00002080static CXString getDeclSpelling(Decl *D) {
2081 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2082 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002083 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002084
Douglas Gregor78205d42010-01-20 21:45:58 +00002085 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002086 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002087
Douglas Gregor78205d42010-01-20 21:45:58 +00002088 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2089 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2090 // and returns different names. NamedDecl returns the class name and
2091 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002092 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002093
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002094 if (isa<UsingDirectiveDecl>(D))
2095 return createCXString("");
2096
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002097 llvm::SmallString<1024> S;
2098 llvm::raw_svector_ostream os(S);
2099 ND->printName(os);
2100
2101 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002102}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002103
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002104CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002105 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002106 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002107
Steve Narofff334b4e2009-09-02 18:26:48 +00002108 if (clang_isReference(C.kind)) {
2109 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002110 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002111 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002112 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002113 }
2114 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002115 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002116 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002117 }
2118 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002119 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002120 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002121 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002122 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002123 case CXCursor_CXXBaseSpecifier: {
2124 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2125 return createCXString(B->getType().getAsString());
2126 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002127 case CXCursor_TypeRef: {
2128 TypeDecl *Type = getCursorTypeRef(C).first;
2129 assert(Type && "Missing type decl");
2130
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002131 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2132 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002133 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002134 case CXCursor_TemplateRef: {
2135 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002136 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002137
2138 return createCXString(Template->getNameAsString());
2139 }
Douglas Gregor69319002010-08-31 23:48:11 +00002140
2141 case CXCursor_NamespaceRef: {
2142 NamedDecl *NS = getCursorNamespaceRef(C).first;
2143 assert(NS && "Missing namespace decl");
2144
2145 return createCXString(NS->getNameAsString());
2146 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002147
Daniel Dunbaracca7252009-11-30 20:42:49 +00002148 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002149 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002150 }
2151 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002152
2153 if (clang_isExpression(C.kind)) {
2154 Decl *D = getDeclFromExpr(getCursorExpr(C));
2155 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002156 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002157 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002158 }
2159
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002160 if (C.kind == CXCursor_MacroInstantiation)
2161 return createCXString(getCursorMacroInstantiation(C)->getName()
2162 ->getNameStart());
2163
Douglas Gregor572feb22010-03-18 18:04:21 +00002164 if (C.kind == CXCursor_MacroDefinition)
2165 return createCXString(getCursorMacroDefinition(C)->getName()
2166 ->getNameStart());
2167
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002168 if (clang_isDeclaration(C.kind))
2169 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002170
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002171 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002172}
2173
Ted Kremeneke68fff62010-02-17 00:41:32 +00002174CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002175 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002176 case CXCursor_FunctionDecl:
2177 return createCXString("FunctionDecl");
2178 case CXCursor_TypedefDecl:
2179 return createCXString("TypedefDecl");
2180 case CXCursor_EnumDecl:
2181 return createCXString("EnumDecl");
2182 case CXCursor_EnumConstantDecl:
2183 return createCXString("EnumConstantDecl");
2184 case CXCursor_StructDecl:
2185 return createCXString("StructDecl");
2186 case CXCursor_UnionDecl:
2187 return createCXString("UnionDecl");
2188 case CXCursor_ClassDecl:
2189 return createCXString("ClassDecl");
2190 case CXCursor_FieldDecl:
2191 return createCXString("FieldDecl");
2192 case CXCursor_VarDecl:
2193 return createCXString("VarDecl");
2194 case CXCursor_ParmDecl:
2195 return createCXString("ParmDecl");
2196 case CXCursor_ObjCInterfaceDecl:
2197 return createCXString("ObjCInterfaceDecl");
2198 case CXCursor_ObjCCategoryDecl:
2199 return createCXString("ObjCCategoryDecl");
2200 case CXCursor_ObjCProtocolDecl:
2201 return createCXString("ObjCProtocolDecl");
2202 case CXCursor_ObjCPropertyDecl:
2203 return createCXString("ObjCPropertyDecl");
2204 case CXCursor_ObjCIvarDecl:
2205 return createCXString("ObjCIvarDecl");
2206 case CXCursor_ObjCInstanceMethodDecl:
2207 return createCXString("ObjCInstanceMethodDecl");
2208 case CXCursor_ObjCClassMethodDecl:
2209 return createCXString("ObjCClassMethodDecl");
2210 case CXCursor_ObjCImplementationDecl:
2211 return createCXString("ObjCImplementationDecl");
2212 case CXCursor_ObjCCategoryImplDecl:
2213 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002214 case CXCursor_CXXMethod:
2215 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002216 case CXCursor_UnexposedDecl:
2217 return createCXString("UnexposedDecl");
2218 case CXCursor_ObjCSuperClassRef:
2219 return createCXString("ObjCSuperClassRef");
2220 case CXCursor_ObjCProtocolRef:
2221 return createCXString("ObjCProtocolRef");
2222 case CXCursor_ObjCClassRef:
2223 return createCXString("ObjCClassRef");
2224 case CXCursor_TypeRef:
2225 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002226 case CXCursor_TemplateRef:
2227 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002228 case CXCursor_NamespaceRef:
2229 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002230 case CXCursor_UnexposedExpr:
2231 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002232 case CXCursor_BlockExpr:
2233 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002234 case CXCursor_DeclRefExpr:
2235 return createCXString("DeclRefExpr");
2236 case CXCursor_MemberRefExpr:
2237 return createCXString("MemberRefExpr");
2238 case CXCursor_CallExpr:
2239 return createCXString("CallExpr");
2240 case CXCursor_ObjCMessageExpr:
2241 return createCXString("ObjCMessageExpr");
2242 case CXCursor_UnexposedStmt:
2243 return createCXString("UnexposedStmt");
2244 case CXCursor_InvalidFile:
2245 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002246 case CXCursor_InvalidCode:
2247 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002248 case CXCursor_NoDeclFound:
2249 return createCXString("NoDeclFound");
2250 case CXCursor_NotImplemented:
2251 return createCXString("NotImplemented");
2252 case CXCursor_TranslationUnit:
2253 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002254 case CXCursor_UnexposedAttr:
2255 return createCXString("UnexposedAttr");
2256 case CXCursor_IBActionAttr:
2257 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002258 case CXCursor_IBOutletAttr:
2259 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002260 case CXCursor_IBOutletCollectionAttr:
2261 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002262 case CXCursor_PreprocessingDirective:
2263 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002264 case CXCursor_MacroDefinition:
2265 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002266 case CXCursor_MacroInstantiation:
2267 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002268 case CXCursor_Namespace:
2269 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002270 case CXCursor_LinkageSpec:
2271 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002272 case CXCursor_CXXBaseSpecifier:
2273 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002274 case CXCursor_Constructor:
2275 return createCXString("CXXConstructor");
2276 case CXCursor_Destructor:
2277 return createCXString("CXXDestructor");
2278 case CXCursor_ConversionFunction:
2279 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002280 case CXCursor_TemplateTypeParameter:
2281 return createCXString("TemplateTypeParameter");
2282 case CXCursor_NonTypeTemplateParameter:
2283 return createCXString("NonTypeTemplateParameter");
2284 case CXCursor_TemplateTemplateParameter:
2285 return createCXString("TemplateTemplateParameter");
2286 case CXCursor_FunctionTemplate:
2287 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002288 case CXCursor_ClassTemplate:
2289 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002290 case CXCursor_ClassTemplatePartialSpecialization:
2291 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002292 case CXCursor_NamespaceAlias:
2293 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002294 case CXCursor_UsingDirective:
2295 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002296 case CXCursor_UsingDeclaration:
2297 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002298 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002299
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002300 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002301 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002302}
Steve Naroff89922f82009-08-31 00:59:03 +00002303
Ted Kremeneke68fff62010-02-17 00:41:32 +00002304enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2305 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002306 CXClientData client_data) {
2307 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2308 *BestCursor = cursor;
2309 return CXChildVisit_Recurse;
2310}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002311
Douglas Gregorb9790342010-01-22 21:44:22 +00002312CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2313 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002314 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002315
Douglas Gregorb9790342010-01-22 21:44:22 +00002316 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002317 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2318
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002319 // Translate the given source location to make it point at the beginning of
2320 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002321 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002322
2323 // Guard against an invalid SourceLocation, or we may assert in one
2324 // of the following calls.
2325 if (SLoc.isInvalid())
2326 return clang_getNullCursor();
2327
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002328 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2329 CXXUnit->getASTContext().getLangOptions());
2330
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002331 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2332 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002333 // FIXME: Would be great to have a "hint" cursor, then walk from that
2334 // hint cursor upward until we find a cursor whose source range encloses
2335 // the region of interest, rather than starting from the translation unit.
2336 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002337 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002338 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002339 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002340 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002341 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002342}
2343
Ted Kremenek73885552009-11-17 19:28:59 +00002344CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002345 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002346}
2347
2348unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002349 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002350}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002351
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002352unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002353 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2354}
2355
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002356unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002357 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2358}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002359
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002360unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002361 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2362}
2363
Douglas Gregor97b98722010-01-19 23:20:36 +00002364unsigned clang_isExpression(enum CXCursorKind K) {
2365 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2366}
2367
2368unsigned clang_isStatement(enum CXCursorKind K) {
2369 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2370}
2371
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002372unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2373 return K == CXCursor_TranslationUnit;
2374}
2375
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002376unsigned clang_isPreprocessing(enum CXCursorKind K) {
2377 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2378}
2379
Ted Kremenekad6eff62010-03-08 21:17:29 +00002380unsigned clang_isUnexposed(enum CXCursorKind K) {
2381 switch (K) {
2382 case CXCursor_UnexposedDecl:
2383 case CXCursor_UnexposedExpr:
2384 case CXCursor_UnexposedStmt:
2385 case CXCursor_UnexposedAttr:
2386 return true;
2387 default:
2388 return false;
2389 }
2390}
2391
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002392CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002393 return C.kind;
2394}
2395
Douglas Gregor98258af2010-01-18 22:46:11 +00002396CXSourceLocation clang_getCursorLocation(CXCursor C) {
2397 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002398 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002399 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002400 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2401 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002402 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002403 }
2404
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002405 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002406 std::pair<ObjCProtocolDecl *, SourceLocation> P
2407 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002408 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002409 }
2410
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002411 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002412 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2413 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002414 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002415 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002416
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002417 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002418 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002419 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002420 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002421
2422 case CXCursor_TemplateRef: {
2423 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2424 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2425 }
2426
Douglas Gregor69319002010-08-31 23:48:11 +00002427 case CXCursor_NamespaceRef: {
2428 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2429 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2430 }
2431
Ted Kremenek3064ef92010-08-27 21:34:58 +00002432 case CXCursor_CXXBaseSpecifier: {
2433 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2434 return clang_getNullLocation();
2435 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002436
Douglas Gregorf46034a2010-01-18 23:41:10 +00002437 default:
2438 // FIXME: Need a way to enumerate all non-reference cases.
2439 llvm_unreachable("Missed a reference kind");
2440 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002441 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002442
2443 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002444 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002445 getLocationFromExpr(getCursorExpr(C)));
2446
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002447 if (C.kind == CXCursor_PreprocessingDirective) {
2448 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2449 return cxloc::translateSourceLocation(getCursorContext(C), L);
2450 }
Douglas Gregor48072312010-03-18 15:23:44 +00002451
2452 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002453 SourceLocation L
2454 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002455 return cxloc::translateSourceLocation(getCursorContext(C), L);
2456 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002457
2458 if (C.kind == CXCursor_MacroDefinition) {
2459 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2460 return cxloc::translateSourceLocation(getCursorContext(C), L);
2461 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002462
Ted Kremenek9a700d22010-05-12 06:16:13 +00002463 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002464 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002465
Douglas Gregorf46034a2010-01-18 23:41:10 +00002466 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002467 SourceLocation Loc = D->getLocation();
2468 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2469 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002470 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002471}
Douglas Gregora7bde202010-01-19 00:34:46 +00002472
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002473} // end extern "C"
2474
2475static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002476 if (clang_isReference(C.kind)) {
2477 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002478 case CXCursor_ObjCSuperClassRef:
2479 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002480
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002481 case CXCursor_ObjCProtocolRef:
2482 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002483
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002484 case CXCursor_ObjCClassRef:
2485 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002486
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002487 case CXCursor_TypeRef:
2488 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002489
2490 case CXCursor_TemplateRef:
2491 return getCursorTemplateRef(C).second;
2492
Douglas Gregor69319002010-08-31 23:48:11 +00002493 case CXCursor_NamespaceRef:
2494 return getCursorNamespaceRef(C).second;
2495
Ted Kremenek3064ef92010-08-27 21:34:58 +00002496 case CXCursor_CXXBaseSpecifier:
2497 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2498 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002499
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002500 default:
2501 // FIXME: Need a way to enumerate all non-reference cases.
2502 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002503 }
2504 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002505
2506 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002507 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002508
2509 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002510 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002511
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002512 if (C.kind == CXCursor_PreprocessingDirective)
2513 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002514
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002515 if (C.kind == CXCursor_MacroInstantiation)
2516 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002517
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002518 if (C.kind == CXCursor_MacroDefinition)
2519 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002520
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002521 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2522 return getCursorDecl(C)->getSourceRange();
2523
2524 return SourceRange();
2525}
2526
2527extern "C" {
2528
2529CXSourceRange clang_getCursorExtent(CXCursor C) {
2530 SourceRange R = getRawCursorExtent(C);
2531 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002532 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002533
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002534 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002535}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002536
2537CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002538 if (clang_isInvalid(C.kind))
2539 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002540
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002541 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002542 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002543 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002544
Douglas Gregor97b98722010-01-19 23:20:36 +00002545 if (clang_isExpression(C.kind)) {
2546 Decl *D = getDeclFromExpr(getCursorExpr(C));
2547 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002548 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002549 return clang_getNullCursor();
2550 }
2551
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002552 if (C.kind == CXCursor_MacroInstantiation) {
2553 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2554 return MakeMacroDefinitionCursor(Def, CXXUnit);
2555 }
2556
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002557 if (!clang_isReference(C.kind))
2558 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002559
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002560 switch (C.kind) {
2561 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002562 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002563
2564 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002565 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002566
2567 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002568 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002569
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002570 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002571 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002572
2573 case CXCursor_TemplateRef:
2574 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2575
Douglas Gregor69319002010-08-31 23:48:11 +00002576 case CXCursor_NamespaceRef:
2577 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2578
Ted Kremenek3064ef92010-08-27 21:34:58 +00002579 case CXCursor_CXXBaseSpecifier: {
2580 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2581 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2582 CXXUnit));
2583 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002584
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002585 default:
2586 // We would prefer to enumerate all non-reference cursor kinds here.
2587 llvm_unreachable("Unhandled reference cursor kind");
2588 break;
2589 }
2590 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002591
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002592 return clang_getNullCursor();
2593}
2594
Douglas Gregorb6998662010-01-19 19:34:47 +00002595CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002596 if (clang_isInvalid(C.kind))
2597 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002598
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002599 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002600
Douglas Gregorb6998662010-01-19 19:34:47 +00002601 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002602 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002603 C = clang_getCursorReferenced(C);
2604 WasReference = true;
2605 }
2606
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002607 if (C.kind == CXCursor_MacroInstantiation)
2608 return clang_getCursorReferenced(C);
2609
Douglas Gregorb6998662010-01-19 19:34:47 +00002610 if (!clang_isDeclaration(C.kind))
2611 return clang_getNullCursor();
2612
2613 Decl *D = getCursorDecl(C);
2614 if (!D)
2615 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002616
Douglas Gregorb6998662010-01-19 19:34:47 +00002617 switch (D->getKind()) {
2618 // Declaration kinds that don't really separate the notions of
2619 // declaration and definition.
2620 case Decl::Namespace:
2621 case Decl::Typedef:
2622 case Decl::TemplateTypeParm:
2623 case Decl::EnumConstant:
2624 case Decl::Field:
2625 case Decl::ObjCIvar:
2626 case Decl::ObjCAtDefsField:
2627 case Decl::ImplicitParam:
2628 case Decl::ParmVar:
2629 case Decl::NonTypeTemplateParm:
2630 case Decl::TemplateTemplateParm:
2631 case Decl::ObjCCategoryImpl:
2632 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002633 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002634 case Decl::LinkageSpec:
2635 case Decl::ObjCPropertyImpl:
2636 case Decl::FileScopeAsm:
2637 case Decl::StaticAssert:
2638 case Decl::Block:
2639 return C;
2640
2641 // Declaration kinds that don't make any sense here, but are
2642 // nonetheless harmless.
2643 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002644 break;
2645
2646 // Declaration kinds for which the definition is not resolvable.
2647 case Decl::UnresolvedUsingTypename:
2648 case Decl::UnresolvedUsingValue:
2649 break;
2650
2651 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002652 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2653 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002654
2655 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002656 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002657
2658 case Decl::Enum:
2659 case Decl::Record:
2660 case Decl::CXXRecord:
2661 case Decl::ClassTemplateSpecialization:
2662 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002663 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002664 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002665 return clang_getNullCursor();
2666
2667 case Decl::Function:
2668 case Decl::CXXMethod:
2669 case Decl::CXXConstructor:
2670 case Decl::CXXDestructor:
2671 case Decl::CXXConversion: {
2672 const FunctionDecl *Def = 0;
2673 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002674 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002675 return clang_getNullCursor();
2676 }
2677
2678 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002679 // Ask the variable if it has a definition.
2680 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2681 return MakeCXCursor(Def, CXXUnit);
2682 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002683 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002684
Douglas Gregorb6998662010-01-19 19:34:47 +00002685 case Decl::FunctionTemplate: {
2686 const FunctionDecl *Def = 0;
2687 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002688 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002689 return clang_getNullCursor();
2690 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002691
Douglas Gregorb6998662010-01-19 19:34:47 +00002692 case Decl::ClassTemplate: {
2693 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002694 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002695 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002696 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002697 return clang_getNullCursor();
2698 }
2699
2700 case Decl::Using: {
2701 UsingDecl *Using = cast<UsingDecl>(D);
2702 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002703 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2704 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002705 S != SEnd; ++S) {
2706 if (Def != clang_getNullCursor()) {
2707 // FIXME: We have no way to return multiple results.
2708 return clang_getNullCursor();
2709 }
2710
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002711 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002712 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002713 }
2714
2715 return Def;
2716 }
2717
2718 case Decl::UsingShadow:
2719 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002720 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002721 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002722
2723 case Decl::ObjCMethod: {
2724 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2725 if (Method->isThisDeclarationADefinition())
2726 return C;
2727
2728 // Dig out the method definition in the associated
2729 // @implementation, if we have it.
2730 // FIXME: The ASTs should make finding the definition easier.
2731 if (ObjCInterfaceDecl *Class
2732 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2733 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2734 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2735 Method->isInstanceMethod()))
2736 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002737 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002738
2739 return clang_getNullCursor();
2740 }
2741
2742 case Decl::ObjCCategory:
2743 if (ObjCCategoryImplDecl *Impl
2744 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002745 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002746 return clang_getNullCursor();
2747
2748 case Decl::ObjCProtocol:
2749 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2750 return C;
2751 return clang_getNullCursor();
2752
2753 case Decl::ObjCInterface:
2754 // There are two notions of a "definition" for an Objective-C
2755 // class: the interface and its implementation. When we resolved a
2756 // reference to an Objective-C class, produce the @interface as
2757 // the definition; when we were provided with the interface,
2758 // produce the @implementation as the definition.
2759 if (WasReference) {
2760 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2761 return C;
2762 } else if (ObjCImplementationDecl *Impl
2763 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002764 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002765 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002766
Douglas Gregorb6998662010-01-19 19:34:47 +00002767 case Decl::ObjCProperty:
2768 // FIXME: We don't really know where to find the
2769 // ObjCPropertyImplDecls that implement this property.
2770 return clang_getNullCursor();
2771
2772 case Decl::ObjCCompatibleAlias:
2773 if (ObjCInterfaceDecl *Class
2774 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2775 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002776 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002777
Douglas Gregorb6998662010-01-19 19:34:47 +00002778 return clang_getNullCursor();
2779
2780 case Decl::ObjCForwardProtocol: {
2781 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2782 if (Forward->protocol_size() == 1)
2783 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002784 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002785 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002786
2787 // FIXME: Cannot return multiple definitions.
2788 return clang_getNullCursor();
2789 }
2790
2791 case Decl::ObjCClass: {
2792 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2793 if (Class->size() == 1) {
2794 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2795 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002796 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002797 return clang_getNullCursor();
2798 }
2799
2800 // FIXME: Cannot return multiple definitions.
2801 return clang_getNullCursor();
2802 }
2803
2804 case Decl::Friend:
2805 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002806 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002807 return clang_getNullCursor();
2808
2809 case Decl::FriendTemplate:
2810 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002811 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002812 return clang_getNullCursor();
2813 }
2814
2815 return clang_getNullCursor();
2816}
2817
2818unsigned clang_isCursorDefinition(CXCursor C) {
2819 if (!clang_isDeclaration(C.kind))
2820 return 0;
2821
2822 return clang_getCursorDefinition(C) == C;
2823}
2824
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002825void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002826 const char **startBuf,
2827 const char **endBuf,
2828 unsigned *startLine,
2829 unsigned *startColumn,
2830 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002831 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002832 assert(getCursorDecl(C) && "CXCursor has null decl");
2833 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002834 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2835 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002836
Steve Naroff4ade6d62009-09-23 17:52:52 +00002837 SourceManager &SM = FD->getASTContext().getSourceManager();
2838 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2839 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2840 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2841 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2842 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2843 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2844}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002845
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002846void clang_enableStackTraces(void) {
2847 llvm::sys::PrintStackTraceOnErrorSignal();
2848}
2849
Ted Kremenekfb480492010-01-13 21:46:36 +00002850} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002851
Ted Kremenekfb480492010-01-13 21:46:36 +00002852//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002853// Token-based Operations.
2854//===----------------------------------------------------------------------===//
2855
2856/* CXToken layout:
2857 * int_data[0]: a CXTokenKind
2858 * int_data[1]: starting token location
2859 * int_data[2]: token length
2860 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002861 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002862 * otherwise unused.
2863 */
2864extern "C" {
2865
2866CXTokenKind clang_getTokenKind(CXToken CXTok) {
2867 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2868}
2869
2870CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2871 switch (clang_getTokenKind(CXTok)) {
2872 case CXToken_Identifier:
2873 case CXToken_Keyword:
2874 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002875 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2876 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002877
2878 case CXToken_Literal: {
2879 // We have stashed the starting pointer in the ptr_data field. Use it.
2880 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002881 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002882 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002883
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002884 case CXToken_Punctuation:
2885 case CXToken_Comment:
2886 break;
2887 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002888
2889 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002890 // deconstructing the source location.
2891 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2892 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002893 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002894
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002895 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2896 std::pair<FileID, unsigned> LocInfo
2897 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002898 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002899 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002900 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2901 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002902 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002903
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002904 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002905}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002906
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002907CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2908 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2909 if (!CXXUnit)
2910 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002911
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002912 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2913 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2914}
2915
2916CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2917 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002918 if (!CXXUnit)
2919 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002920
2921 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002922 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2923}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002924
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002925void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2926 CXToken **Tokens, unsigned *NumTokens) {
2927 if (Tokens)
2928 *Tokens = 0;
2929 if (NumTokens)
2930 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002931
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002932 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2933 if (!CXXUnit || !Tokens || !NumTokens)
2934 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002935
Douglas Gregorbdf60622010-03-05 21:16:25 +00002936 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2937
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002938 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002939 if (R.isInvalid())
2940 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002941
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002942 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2943 std::pair<FileID, unsigned> BeginLocInfo
2944 = SourceMgr.getDecomposedLoc(R.getBegin());
2945 std::pair<FileID, unsigned> EndLocInfo
2946 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002947
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002948 // Cannot tokenize across files.
2949 if (BeginLocInfo.first != EndLocInfo.first)
2950 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002951
2952 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002953 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002954 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002955 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002956 if (Invalid)
2957 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002958
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002959 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2960 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002961 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002962 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002963
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002964 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002965 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002966 llvm::SmallVector<CXToken, 32> CXTokens;
2967 Token Tok;
2968 do {
2969 // Lex the next token
2970 Lex.LexFromRawLexer(Tok);
2971 if (Tok.is(tok::eof))
2972 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002973
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002974 // Initialize the CXToken.
2975 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002976
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002977 // - Common fields
2978 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2979 CXTok.int_data[2] = Tok.getLength();
2980 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002981
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002982 // - Kind-specific fields
2983 if (Tok.isLiteral()) {
2984 CXTok.int_data[0] = CXToken_Literal;
2985 CXTok.ptr_data = (void *)Tok.getLiteralData();
2986 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002987 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002988 std::pair<FileID, unsigned> LocInfo
2989 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002990 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002991 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002992 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2993 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002994 return;
2995
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002996 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002997 IdentifierInfo *II
2998 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002999
3000 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3001 CXTok.int_data[0] = CXToken_Keyword;
3002 }
3003 else {
3004 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3005 CXToken_Identifier
3006 : CXToken_Keyword;
3007 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003008 CXTok.ptr_data = II;
3009 } else if (Tok.is(tok::comment)) {
3010 CXTok.int_data[0] = CXToken_Comment;
3011 CXTok.ptr_data = 0;
3012 } else {
3013 CXTok.int_data[0] = CXToken_Punctuation;
3014 CXTok.ptr_data = 0;
3015 }
3016 CXTokens.push_back(CXTok);
3017 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003018
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003019 if (CXTokens.empty())
3020 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003021
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003022 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3023 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3024 *NumTokens = CXTokens.size();
3025}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003026
Ted Kremenek6db61092010-05-05 00:55:15 +00003027void clang_disposeTokens(CXTranslationUnit TU,
3028 CXToken *Tokens, unsigned NumTokens) {
3029 free(Tokens);
3030}
3031
3032} // end: extern "C"
3033
3034//===----------------------------------------------------------------------===//
3035// Token annotation APIs.
3036//===----------------------------------------------------------------------===//
3037
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003038typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003039static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3040 CXCursor parent,
3041 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003042namespace {
3043class AnnotateTokensWorker {
3044 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003045 CXToken *Tokens;
3046 CXCursor *Cursors;
3047 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003048 unsigned TokIdx;
3049 CursorVisitor AnnotateVis;
3050 SourceManager &SrcMgr;
3051
3052 bool MoreTokens() const { return TokIdx < NumTokens; }
3053 unsigned NextToken() const { return TokIdx; }
3054 void AdvanceToken() { ++TokIdx; }
3055 SourceLocation GetTokenLoc(unsigned tokI) {
3056 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3057 }
3058
Ted Kremenek6db61092010-05-05 00:55:15 +00003059public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003060 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003061 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3062 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003063 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003064 NumTokens(numTokens), TokIdx(0),
3065 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3066 Decl::MaxPCHLevel, RegionOfInterest),
3067 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003068
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003069 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003070 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003071 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003072};
3073}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003074
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003075void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3076 // Walk the AST within the region of interest, annotating tokens
3077 // along the way.
3078 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003079
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003080 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3081 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3082 if (Pos != Annotated.end())
3083 Cursors[I] = Pos->second;
3084 }
3085
3086 // Finish up annotating any tokens left.
3087 if (!MoreTokens())
3088 return;
3089
3090 const CXCursor &C = clang_getNullCursor();
3091 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3092 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3093 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003094 }
3095}
3096
Ted Kremenek6db61092010-05-05 00:55:15 +00003097enum CXChildVisitResult
3098AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003099 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3100 // We can always annotate a preprocessing directive/macro instantiation.
3101 if (clang_isPreprocessing(cursor.kind)) {
3102 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003103 return CXChildVisit_Recurse;
3104 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003105
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003106 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003107
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003108 if (cursorRange.isInvalid())
3109 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003110
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003111 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3112
Ted Kremeneka333c662010-05-12 05:29:33 +00003113 // Adjust the annotated range based specific declarations.
3114 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3115 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003116 Decl *D = cxcursor::getCursorDecl(cursor);
3117 // Don't visit synthesized ObjC methods, since they have no syntatic
3118 // representation in the source.
3119 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3120 if (MD->isSynthesized())
3121 return CXChildVisit_Continue;
3122 }
3123 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003124 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3125 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003126 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003127 if (TLoc.isValid() &&
3128 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003129 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003130 }
3131 }
3132 }
3133
Ted Kremenek3f404602010-08-14 01:14:06 +00003134 // If the location of the cursor occurs within a macro instantiation, record
3135 // the spelling location of the cursor in our annotation map. We can then
3136 // paper over the token labelings during a post-processing step to try and
3137 // get cursor mappings for tokens that are the *arguments* of a macro
3138 // instantiation.
3139 if (L.isMacroID()) {
3140 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3141 // Only invalidate the old annotation if it isn't part of a preprocessing
3142 // directive. Here we assume that the default construction of CXCursor
3143 // results in CXCursor.kind being an initialized value (i.e., 0). If
3144 // this isn't the case, we can fix by doing lookup + insertion.
3145
3146 CXCursor &oldC = Annotated[rawEncoding];
3147 if (!clang_isPreprocessing(oldC.kind))
3148 oldC = cursor;
3149 }
3150
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003151 const enum CXCursorKind K = clang_getCursorKind(parent);
3152 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003153 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3154 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003155
3156 while (MoreTokens()) {
3157 const unsigned I = NextToken();
3158 SourceLocation TokLoc = GetTokenLoc(I);
3159 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3160 case RangeBefore:
3161 Cursors[I] = updateC;
3162 AdvanceToken();
3163 continue;
3164 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003165 case RangeOverlap:
3166 break;
3167 }
3168 break;
3169 }
3170
3171 // Visit children to get their cursor information.
3172 const unsigned BeforeChildren = NextToken();
3173 VisitChildren(cursor);
3174 const unsigned AfterChildren = NextToken();
3175
3176 // Adjust 'Last' to the last token within the extent of the cursor.
3177 while (MoreTokens()) {
3178 const unsigned I = NextToken();
3179 SourceLocation TokLoc = GetTokenLoc(I);
3180 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3181 case RangeBefore:
3182 assert(0 && "Infeasible");
3183 case RangeAfter:
3184 break;
3185 case RangeOverlap:
3186 Cursors[I] = updateC;
3187 AdvanceToken();
3188 continue;
3189 }
3190 break;
3191 }
3192 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003193
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003194 // Scan the tokens that are at the beginning of the cursor, but are not
3195 // capture by the child cursors.
3196
3197 // For AST elements within macros, rely on a post-annotate pass to
3198 // to correctly annotate the tokens with cursors. Otherwise we can
3199 // get confusing results of having tokens that map to cursors that really
3200 // are expanded by an instantiation.
3201 if (L.isMacroID())
3202 cursor = clang_getNullCursor();
3203
3204 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3205 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3206 break;
3207 Cursors[I] = cursor;
3208 }
3209 // Scan the tokens that are at the end of the cursor, but are not captured
3210 // but the child cursors.
3211 for (unsigned I = AfterChildren; I != Last; ++I)
3212 Cursors[I] = cursor;
3213
3214 TokIdx = Last;
3215 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003216}
3217
Ted Kremenek6db61092010-05-05 00:55:15 +00003218static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3219 CXCursor parent,
3220 CXClientData client_data) {
3221 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3222}
3223
3224extern "C" {
3225
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003226void clang_annotateTokens(CXTranslationUnit TU,
3227 CXToken *Tokens, unsigned NumTokens,
3228 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003229
3230 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003231 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003232
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003233 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003234 if (!CXXUnit) {
3235 // Any token we don't specifically annotate will have a NULL cursor.
3236 const CXCursor &C = clang_getNullCursor();
3237 for (unsigned I = 0; I != NumTokens; ++I)
3238 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003239 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003240 }
3241
Douglas Gregorbdf60622010-03-05 21:16:25 +00003242 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003243
Douglas Gregor0396f462010-03-19 05:22:59 +00003244 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003245 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003246 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3247 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003248 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3249 clang_getTokenLocation(TU,
3250 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003251
Douglas Gregor0396f462010-03-19 05:22:59 +00003252 // A mapping from the source locations found when re-lexing or traversing the
3253 // region of interest to the corresponding cursors.
3254 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003255
3256 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003257 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003258 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3259 std::pair<FileID, unsigned> BeginLocInfo
3260 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3261 std::pair<FileID, unsigned> EndLocInfo
3262 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003263
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003264 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003265 bool Invalid = false;
3266 if (BeginLocInfo.first == EndLocInfo.first &&
3267 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3268 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003269 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3270 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003271 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003272 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003273 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003274
3275 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003276 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003277 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003278 Token Tok;
3279 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003280
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003281 reprocess:
3282 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3283 // We have found a preprocessing directive. Gobble it up so that we
3284 // don't see it while preprocessing these tokens later, but keep track of
3285 // all of the token locations inside this preprocessing directive so that
3286 // we can annotate them appropriately.
3287 //
3288 // FIXME: Some simple tests here could identify macro definitions and
3289 // #undefs, to provide specific cursor kinds for those.
3290 std::vector<SourceLocation> Locations;
3291 do {
3292 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003293 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003294 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003295
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003296 using namespace cxcursor;
3297 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003298 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3299 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003300 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003301 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3302 Annotated[Locations[I].getRawEncoding()] = Cursor;
3303 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003304
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003305 if (Tok.isAtStartOfLine())
3306 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003307
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003308 continue;
3309 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003310
Douglas Gregor48072312010-03-18 15:23:44 +00003311 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003312 break;
3313 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003314 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003315
Douglas Gregor0396f462010-03-19 05:22:59 +00003316 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003317 // a specific cursor.
3318 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3319 CXXUnit, RegionOfInterest);
3320 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003321}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003322} // end: extern "C"
3323
3324//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003325// Operations for querying linkage of a cursor.
3326//===----------------------------------------------------------------------===//
3327
3328extern "C" {
3329CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003330 if (!clang_isDeclaration(cursor.kind))
3331 return CXLinkage_Invalid;
3332
Ted Kremenek16b42592010-03-03 06:36:57 +00003333 Decl *D = cxcursor::getCursorDecl(cursor);
3334 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3335 switch (ND->getLinkage()) {
3336 case NoLinkage: return CXLinkage_NoLinkage;
3337 case InternalLinkage: return CXLinkage_Internal;
3338 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3339 case ExternalLinkage: return CXLinkage_External;
3340 };
3341
3342 return CXLinkage_Invalid;
3343}
3344} // end: extern "C"
3345
3346//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003347// Operations for querying language of a cursor.
3348//===----------------------------------------------------------------------===//
3349
3350static CXLanguageKind getDeclLanguage(const Decl *D) {
3351 switch (D->getKind()) {
3352 default:
3353 break;
3354 case Decl::ImplicitParam:
3355 case Decl::ObjCAtDefsField:
3356 case Decl::ObjCCategory:
3357 case Decl::ObjCCategoryImpl:
3358 case Decl::ObjCClass:
3359 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003360 case Decl::ObjCForwardProtocol:
3361 case Decl::ObjCImplementation:
3362 case Decl::ObjCInterface:
3363 case Decl::ObjCIvar:
3364 case Decl::ObjCMethod:
3365 case Decl::ObjCProperty:
3366 case Decl::ObjCPropertyImpl:
3367 case Decl::ObjCProtocol:
3368 return CXLanguage_ObjC;
3369 case Decl::CXXConstructor:
3370 case Decl::CXXConversion:
3371 case Decl::CXXDestructor:
3372 case Decl::CXXMethod:
3373 case Decl::CXXRecord:
3374 case Decl::ClassTemplate:
3375 case Decl::ClassTemplatePartialSpecialization:
3376 case Decl::ClassTemplateSpecialization:
3377 case Decl::Friend:
3378 case Decl::FriendTemplate:
3379 case Decl::FunctionTemplate:
3380 case Decl::LinkageSpec:
3381 case Decl::Namespace:
3382 case Decl::NamespaceAlias:
3383 case Decl::NonTypeTemplateParm:
3384 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003385 case Decl::TemplateTemplateParm:
3386 case Decl::TemplateTypeParm:
3387 case Decl::UnresolvedUsingTypename:
3388 case Decl::UnresolvedUsingValue:
3389 case Decl::Using:
3390 case Decl::UsingDirective:
3391 case Decl::UsingShadow:
3392 return CXLanguage_CPlusPlus;
3393 }
3394
3395 return CXLanguage_C;
3396}
3397
3398extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003399
3400enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3401 if (clang_isDeclaration(cursor.kind))
3402 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3403 if (D->hasAttr<UnavailableAttr>() ||
3404 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3405 return CXAvailability_Available;
3406
3407 if (D->hasAttr<DeprecatedAttr>())
3408 return CXAvailability_Deprecated;
3409 }
3410
3411 return CXAvailability_Available;
3412}
3413
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003414CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3415 if (clang_isDeclaration(cursor.kind))
3416 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3417
3418 return CXLanguage_Invalid;
3419}
3420} // end: extern "C"
3421
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003422
3423//===----------------------------------------------------------------------===//
3424// C++ AST instrospection.
3425//===----------------------------------------------------------------------===//
3426
3427extern "C" {
3428unsigned clang_CXXMethod_isStatic(CXCursor C) {
3429 if (!clang_isDeclaration(C.kind))
3430 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003431
3432 CXXMethodDecl *Method = 0;
3433 Decl *D = cxcursor::getCursorDecl(C);
3434 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3435 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3436 else
3437 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3438 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003439}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003440
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003441} // end: extern "C"
3442
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003443//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003444// Attribute introspection.
3445//===----------------------------------------------------------------------===//
3446
3447extern "C" {
3448CXType clang_getIBOutletCollectionType(CXCursor C) {
3449 if (C.kind != CXCursor_IBOutletCollectionAttr)
3450 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3451
3452 IBOutletCollectionAttr *A =
3453 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3454
3455 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3456}
3457} // end: extern "C"
3458
3459//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003460// CXString Operations.
3461//===----------------------------------------------------------------------===//
3462
3463extern "C" {
3464const char *clang_getCString(CXString string) {
3465 return string.Spelling;
3466}
3467
3468void clang_disposeString(CXString string) {
3469 if (string.MustFreeString && string.Spelling)
3470 free((void*)string.Spelling);
3471}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003472
Ted Kremenekfb480492010-01-13 21:46:36 +00003473} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003474
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003475namespace clang { namespace cxstring {
3476CXString createCXString(const char *String, bool DupString){
3477 CXString Str;
3478 if (DupString) {
3479 Str.Spelling = strdup(String);
3480 Str.MustFreeString = 1;
3481 } else {
3482 Str.Spelling = String;
3483 Str.MustFreeString = 0;
3484 }
3485 return Str;
3486}
3487
3488CXString createCXString(llvm::StringRef String, bool DupString) {
3489 CXString Result;
3490 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3491 char *Spelling = (char *)malloc(String.size() + 1);
3492 memmove(Spelling, String.data(), String.size());
3493 Spelling[String.size()] = 0;
3494 Result.Spelling = Spelling;
3495 Result.MustFreeString = 1;
3496 } else {
3497 Result.Spelling = String.data();
3498 Result.MustFreeString = 0;
3499 }
3500 return Result;
3501}
3502}}
3503
Ted Kremenek04bb7162010-01-22 22:44:15 +00003504//===----------------------------------------------------------------------===//
3505// Misc. utility functions.
3506//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003507
Ted Kremenek04bb7162010-01-22 22:44:15 +00003508extern "C" {
3509
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003510CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003511 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003512}
3513
3514} // end: extern "C"