blob: 230631bad9a70f9d420e58b1c73af6e161214f39 [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 Gregor74dbe642010-08-31 19:31:58 +0000293 bool VisitClassTemplatePartialSpecializationDecl(
294 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000295 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000296 bool VisitEnumConstantDecl(EnumConstantDecl *D);
297 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
298 bool VisitFunctionDecl(FunctionDecl *ND);
299 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000300 bool VisitVarDecl(VarDecl *);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000301 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000302 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000303 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
304 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
305 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
306 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000307 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000308 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
309 bool VisitObjCImplDecl(ObjCImplDecl *D);
310 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
311 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
312 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
313 // etc.
314 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
315 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
316 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000317 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000318 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000319 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000320
Douglas Gregor01829d32010-08-31 14:41:23 +0000321 // Name visitor
322 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
323
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000324 // Template visitors
325 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000326 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000327 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
328
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000329 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000330 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000331 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000332 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000333 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
334 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000335 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000336 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000337 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000338 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
339 bool VisitPointerTypeLoc(PointerTypeLoc TL);
340 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
341 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
342 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
343 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000344 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000345 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000346 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000347 // FIXME: Implement visitors here when the unimplemented TypeLocs get
348 // implemented
349 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
350 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000351
Douglas Gregora59e3902010-01-21 23:27:09 +0000352 // Statement visitors
353 bool VisitStmt(Stmt *S);
354 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000355 // FIXME: LabelStmt label?
356 bool VisitIfStmt(IfStmt *S);
357 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000358 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000359 bool VisitWhileStmt(WhileStmt *S);
360 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000361// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000362
Douglas Gregor336fd812010-01-23 00:40:08 +0000363 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000364 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
365 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000366 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000367 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000368 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000369 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000370 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000371 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000372 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000373 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000374 // FIXME: AddrLabelExpr (once we have cursors for labels)
375 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
376 bool VisitVAArgExpr(VAArgExpr *E);
377 // FIXME: InitListExpr (for the designators)
378 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000379};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000380
Ted Kremenekab188932010-01-05 19:32:54 +0000381} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000382
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000383static SourceRange getRawCursorExtent(CXCursor C);
384
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000386 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
387}
388
Douglas Gregorb1373d02010-01-20 20:59:29 +0000389/// \brief Visit the given cursor and, if requested by the visitor,
390/// its children.
391///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000392/// \param Cursor the cursor to visit.
393///
394/// \param CheckRegionOfInterest if true, then the caller already checked that
395/// this cursor is within the region of interest.
396///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000397/// \returns true if the visitation should be aborted, false if it
398/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000399bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400 if (clang_isInvalid(Cursor.kind))
401 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000402
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403 if (clang_isDeclaration(Cursor.kind)) {
404 Decl *D = getCursorDecl(Cursor);
405 assert(D && "Invalid declaration cursor");
406 if (D->getPCHLevel() > MaxPCHLevel)
407 return false;
408
409 if (D->isImplicit())
410 return false;
411 }
412
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000413 // If we have a range of interest, and this cursor doesn't intersect with it,
414 // we're done.
415 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000416 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000417 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000418 return false;
419 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000420
Douglas Gregorb1373d02010-01-20 20:59:29 +0000421 switch (Visitor(Cursor, Parent, ClientData)) {
422 case CXChildVisit_Break:
423 return true;
424
425 case CXChildVisit_Continue:
426 return false;
427
428 case CXChildVisit_Recurse:
429 return VisitChildren(Cursor);
430 }
431
Douglas Gregorfd643772010-01-25 16:45:46 +0000432 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000433}
434
Douglas Gregor788f5a12010-03-20 00:41:21 +0000435std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
436CursorVisitor::getPreprocessedEntities() {
437 PreprocessingRecord &PPRec
438 = *TU->getPreprocessor().getPreprocessingRecord();
439
440 bool OnlyLocalDecls
441 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
442
443 // There is no region of interest; we have to walk everything.
444 if (RegionOfInterest.isInvalid())
445 return std::make_pair(PPRec.begin(OnlyLocalDecls),
446 PPRec.end(OnlyLocalDecls));
447
448 // Find the file in which the region of interest lands.
449 SourceManager &SM = TU->getSourceManager();
450 std::pair<FileID, unsigned> Begin
451 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
452 std::pair<FileID, unsigned> End
453 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
454
455 // The region of interest spans files; we have to walk everything.
456 if (Begin.first != End.first)
457 return std::make_pair(PPRec.begin(OnlyLocalDecls),
458 PPRec.end(OnlyLocalDecls));
459
460 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
461 = TU->getPreprocessedEntitiesByFile();
462 if (ByFileMap.empty()) {
463 // Build the mapping from files to sets of preprocessed entities.
464 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
465 EEnd = PPRec.end(OnlyLocalDecls);
466 E != EEnd; ++E) {
467 std::pair<FileID, unsigned> P
468 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
469 ByFileMap[P.first].push_back(*E);
470 }
471 }
472
473 return std::make_pair(ByFileMap[Begin.first].begin(),
474 ByFileMap[Begin.first].end());
475}
476
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477/// \brief Visit the children of the given cursor.
478///
479/// \returns true if the visitation should be aborted, false if it
480/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000481bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000482 if (clang_isReference(Cursor.kind)) {
483 // By definition, references have no children.
484 return false;
485 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000486
487 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000488 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000489 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000490
Douglas Gregorb1373d02010-01-20 20:59:29 +0000491 if (clang_isDeclaration(Cursor.kind)) {
492 Decl *D = getCursorDecl(Cursor);
493 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000494 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000496
Douglas Gregora59e3902010-01-21 23:27:09 +0000497 if (clang_isStatement(Cursor.kind))
498 return Visit(getCursorStmt(Cursor));
499 if (clang_isExpression(Cursor.kind))
500 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000501
Douglas Gregorb1373d02010-01-20 20:59:29 +0000502 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000503 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000504 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
505 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000506 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
507 TLEnd = CXXUnit->top_level_end();
508 TL != TLEnd; ++TL) {
509 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000510 return true;
511 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000512 } else if (VisitDeclContext(
513 CXXUnit->getASTContext().getTranslationUnitDecl()))
514 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000515
Douglas Gregor0396f462010-03-19 05:22:59 +0000516 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000517 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000518 // FIXME: Once we have the ability to deserialize a preprocessing record,
519 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000520 PreprocessingRecord::iterator E, EEnd;
521 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000522 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
523 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
524 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000525
Douglas Gregor0396f462010-03-19 05:22:59 +0000526 continue;
527 }
528
529 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
530 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
531 return true;
532
533 continue;
534 }
535 }
536 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000537 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000538 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000539
Douglas Gregorb1373d02010-01-20 20:59:29 +0000540 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000541 return false;
542}
543
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000544bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000545 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
546 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000547
Ted Kremenek664cffd2010-07-22 11:30:19 +0000548 if (Stmt *Body = B->getBody())
549 return Visit(MakeCXCursor(Body, StmtParent, TU));
550
551 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000552}
553
Douglas Gregorb1373d02010-01-20 20:59:29 +0000554bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000555 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000556 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000557
Ted Kremenek23173d72010-05-18 21:09:07 +0000558 Decl *D = *I;
559 if (D->getLexicalDeclContext() != DC)
560 continue;
561
562 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000563
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000564 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000565 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000566 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000567 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000568
569 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000570 case RangeBefore:
571 // This declaration comes before the region of interest; skip it.
572 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000573
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000574 case RangeAfter:
575 // This declaration comes after the region of interest; we're done.
576 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000577
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000578 case RangeOverlap:
579 // This declaration overlaps the region of interest; visit it.
580 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000581 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000582 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000583
Daniel Dunbard52864b2010-02-14 10:02:57 +0000584 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000585 return true;
586 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000587
Douglas Gregorb1373d02010-01-20 20:59:29 +0000588 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000589}
590
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000591bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
592 llvm_unreachable("Translation units are visited directly by Visit()");
593 return false;
594}
595
596bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
597 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
598 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000599
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000600 return false;
601}
602
603bool CursorVisitor::VisitTagDecl(TagDecl *D) {
604 return VisitDeclContext(D);
605}
606
Douglas Gregor74dbe642010-08-31 19:31:58 +0000607bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
608 ClassTemplatePartialSpecializationDecl *D) {
609 // FIXME: Visit the "outer" template parameter lists on the TagDecl
610 // before visiting these template parameters.
611 if (VisitTemplateParameters(D->getTemplateParameters()))
612 return true;
613
614 // Visit the partial specialization arguments.
615 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
616 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
617 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
618 return true;
619
620 return VisitCXXRecordDecl(D);
621}
622
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000623bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
624 // FIXME: Visit default argument
625 return false;
626}
627
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000628bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
629 if (Expr *Init = D->getInitExpr())
630 return Visit(MakeCXCursor(Init, StmtParent, TU));
631 return false;
632}
633
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000634bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
635 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
636 if (Visit(TSInfo->getTypeLoc()))
637 return true;
638
639 return false;
640}
641
Douglas Gregorb1373d02010-01-20 20:59:29 +0000642bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000643 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
644 // Visit the function declaration's syntactic components in the order
645 // written. This requires a bit of work.
646 TypeLoc TL = TSInfo->getTypeLoc();
647 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
648
649 // If we have a function declared directly (without the use of a typedef),
650 // visit just the return type. Otherwise, just visit the function's type
651 // now.
652 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
653 (!FTL && Visit(TL)))
654 return true;
655
656 // FIXME: Visit the nested-name-specifier, if present.
657
658 // Visit the declaration name.
659 if (VisitDeclarationNameInfo(ND->getNameInfo()))
660 return true;
661
662 // FIXME: Visit explicitly-specified template arguments!
663
664 // Visit the function parameters, if we have a function type.
665 if (FTL && VisitFunctionTypeLoc(*FTL, true))
666 return true;
667
668 // FIXME: Attributes?
669 }
670
Douglas Gregora59e3902010-01-21 23:27:09 +0000671 if (ND->isThisDeclarationADefinition() &&
672 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
673 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000674
Douglas Gregorb1373d02010-01-20 20:59:29 +0000675 return false;
676}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000677
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000678bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
679 if (VisitDeclaratorDecl(D))
680 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000681
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000682 if (Expr *BitWidth = D->getBitWidth())
683 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000684
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000685 return false;
686}
687
688bool CursorVisitor::VisitVarDecl(VarDecl *D) {
689 if (VisitDeclaratorDecl(D))
690 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000691
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000692 if (Expr *Init = D->getInit())
693 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000694
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000695 return false;
696}
697
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000698bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
699 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
700 // before visiting these template parameters.
701 if (VisitTemplateParameters(D->getTemplateParameters()))
702 return true;
703
704 return VisitFunctionDecl(D->getTemplatedDecl());
705}
706
Douglas Gregor39d6f072010-08-31 19:02:00 +0000707bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
708 // FIXME: Visit the "outer" template parameter lists on the TagDecl
709 // before visiting these template parameters.
710 if (VisitTemplateParameters(D->getTemplateParameters()))
711 return true;
712
713 return VisitCXXRecordDecl(D->getTemplatedDecl());
714}
715
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000716bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000717 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
718 if (Visit(TSInfo->getTypeLoc()))
719 return true;
720
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000721 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000722 PEnd = ND->param_end();
723 P != PEnd; ++P) {
724 if (Visit(MakeCXCursor(*P, TU)))
725 return true;
726 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000727
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000728 if (ND->isThisDeclarationADefinition() &&
729 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
730 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000731
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000732 return false;
733}
734
Douglas Gregora59e3902010-01-21 23:27:09 +0000735bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
736 return VisitDeclContext(D);
737}
738
Douglas Gregorb1373d02010-01-20 20:59:29 +0000739bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000740 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
741 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000742 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000743
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000744 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
745 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
746 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000747 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000748 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000749
Douglas Gregora59e3902010-01-21 23:27:09 +0000750 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000751}
752
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000753bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
754 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
755 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
756 E = PID->protocol_end(); I != E; ++I, ++PL)
757 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
758 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000759
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000760 return VisitObjCContainerDecl(PID);
761}
762
Ted Kremenek23173d72010-05-18 21:09:07 +0000763bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000764 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
765 return true;
766
Ted Kremenek23173d72010-05-18 21:09:07 +0000767 // FIXME: This implements a workaround with @property declarations also being
768 // installed in the DeclContext for the @interface. Eventually this code
769 // should be removed.
770 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
771 if (!CDecl || !CDecl->IsClassExtension())
772 return false;
773
774 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
775 if (!ID)
776 return false;
777
778 IdentifierInfo *PropertyId = PD->getIdentifier();
779 ObjCPropertyDecl *prevDecl =
780 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
781
782 if (!prevDecl)
783 return false;
784
785 // Visit synthesized methods since they will be skipped when visiting
786 // the @interface.
787 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
788 if (MD->isSynthesized())
789 if (Visit(MakeCXCursor(MD, TU)))
790 return true;
791
792 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
793 if (MD->isSynthesized())
794 if (Visit(MakeCXCursor(MD, TU)))
795 return true;
796
797 return false;
798}
799
Douglas Gregorb1373d02010-01-20 20:59:29 +0000800bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000801 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000802 if (D->getSuperClass() &&
803 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000805 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000806 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000807
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000808 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
809 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
810 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000811 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000812 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000813
Douglas Gregora59e3902010-01-21 23:27:09 +0000814 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000815}
816
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000817bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
818 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000819}
820
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000821bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000822 // 'ID' could be null when dealing with invalid code.
823 if (ObjCInterfaceDecl *ID = D->getClassInterface())
824 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
825 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000826
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000827 return VisitObjCImplDecl(D);
828}
829
830bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
831#if 0
832 // Issue callbacks for super class.
833 // FIXME: No source location information!
834 if (D->getSuperClass() &&
835 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000836 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000837 TU)))
838 return true;
839#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000840
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000841 return VisitObjCImplDecl(D);
842}
843
844bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
845 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
846 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
847 E = D->protocol_end();
848 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000849 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000850 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000851
852 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000853}
854
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000855bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
856 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
857 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
858 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000859
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000860 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000861}
862
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000863bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
864 return VisitDeclContext(D);
865}
866
Douglas Gregor69319002010-08-31 23:48:11 +0000867bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
868 // FIXME: Visit nested-name-specifier
869
870 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
871 D->getTargetNameLoc(), TU));
872}
873
Douglas Gregor01829d32010-08-31 14:41:23 +0000874bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
875 switch (Name.getName().getNameKind()) {
876 case clang::DeclarationName::Identifier:
877 case clang::DeclarationName::CXXLiteralOperatorName:
878 case clang::DeclarationName::CXXOperatorName:
879 case clang::DeclarationName::CXXUsingDirective:
880 return false;
881
882 case clang::DeclarationName::CXXConstructorName:
883 case clang::DeclarationName::CXXDestructorName:
884 case clang::DeclarationName::CXXConversionFunctionName:
885 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
886 return Visit(TSInfo->getTypeLoc());
887 return false;
888
889 case clang::DeclarationName::ObjCZeroArgSelector:
890 case clang::DeclarationName::ObjCOneArgSelector:
891 case clang::DeclarationName::ObjCMultiArgSelector:
892 // FIXME: Per-identifier location info?
893 return false;
894 }
895
896 return false;
897}
898
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000899bool CursorVisitor::VisitTemplateParameters(
900 const TemplateParameterList *Params) {
901 if (!Params)
902 return false;
903
904 for (TemplateParameterList::const_iterator P = Params->begin(),
905 PEnd = Params->end();
906 P != PEnd; ++P) {
907 if (Visit(MakeCXCursor(*P, TU)))
908 return true;
909 }
910
911 return false;
912}
913
Douglas Gregor0b36e612010-08-31 20:37:03 +0000914bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
915 switch (Name.getKind()) {
916 case TemplateName::Template:
917 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
918
919 case TemplateName::OverloadedTemplate:
920 // FIXME: We need a way to return multiple lookup results in a single
921 // cursor.
922 return false;
923
924 case TemplateName::DependentTemplate:
925 // FIXME: Visit nested-name-specifier.
926 return false;
927
928 case TemplateName::QualifiedTemplate:
929 // FIXME: Visit nested-name-specifier.
930 return Visit(MakeCursorTemplateRef(
931 Name.getAsQualifiedTemplateName()->getDecl(),
932 Loc, TU));
933 }
934
935 return false;
936}
937
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000938bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
939 switch (TAL.getArgument().getKind()) {
940 case TemplateArgument::Null:
941 case TemplateArgument::Integral:
942 return false;
943
944 case TemplateArgument::Pack:
945 // FIXME: Implement when variadic templates come along.
946 return false;
947
948 case TemplateArgument::Type:
949 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
950 return Visit(TSInfo->getTypeLoc());
951 return false;
952
953 case TemplateArgument::Declaration:
954 if (Expr *E = TAL.getSourceDeclExpression())
955 return Visit(MakeCXCursor(E, StmtParent, TU));
956 return false;
957
958 case TemplateArgument::Expression:
959 if (Expr *E = TAL.getSourceExpression())
960 return Visit(MakeCXCursor(E, StmtParent, TU));
961 return false;
962
963 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +0000964 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
965 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000966 }
967
968 return false;
969}
970
Ted Kremeneka0536d82010-05-07 01:04:29 +0000971bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
972 return VisitDeclContext(D);
973}
974
Douglas Gregor01829d32010-08-31 14:41:23 +0000975bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
976 return Visit(TL.getUnqualifiedLoc());
977}
978
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000979bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
980 ASTContext &Context = TU->getASTContext();
981
982 // Some builtin types (such as Objective-C's "id", "sel", and
983 // "Class") have associated declarations. Create cursors for those.
984 QualType VisitType;
985 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000986 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000987 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000988 case BuiltinType::Char_U:
989 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000990 case BuiltinType::Char16:
991 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000992 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000993 case BuiltinType::UInt:
994 case BuiltinType::ULong:
995 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000996 case BuiltinType::UInt128:
997 case BuiltinType::Char_S:
998 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000999 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001000 case BuiltinType::Short:
1001 case BuiltinType::Int:
1002 case BuiltinType::Long:
1003 case BuiltinType::LongLong:
1004 case BuiltinType::Int128:
1005 case BuiltinType::Float:
1006 case BuiltinType::Double:
1007 case BuiltinType::LongDouble:
1008 case BuiltinType::NullPtr:
1009 case BuiltinType::Overload:
1010 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001011 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001012
1013 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001014 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001015
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001016 case BuiltinType::ObjCId:
1017 VisitType = Context.getObjCIdType();
1018 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001019
1020 case BuiltinType::ObjCClass:
1021 VisitType = Context.getObjCClassType();
1022 break;
1023
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001024 case BuiltinType::ObjCSel:
1025 VisitType = Context.getObjCSelType();
1026 break;
1027 }
1028
1029 if (!VisitType.isNull()) {
1030 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001031 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001032 TU));
1033 }
1034
1035 return false;
1036}
1037
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001038bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1039 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1040}
1041
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001042bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1043 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1044}
1045
1046bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1047 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1048}
1049
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001050bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1051 // FIXME: We can't visit the template template parameter, but there's
1052 // no context information with which we can match up the depth/index in the
1053 // type to the appropriate
1054 return false;
1055}
1056
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001057bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1058 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1059 return true;
1060
John McCallc12c5bb2010-05-15 11:32:37 +00001061 return false;
1062}
1063
1064bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1065 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1066 return true;
1067
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001068 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1069 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1070 TU)))
1071 return true;
1072 }
1073
1074 return false;
1075}
1076
1077bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001078 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001079}
1080
1081bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1082 return Visit(TL.getPointeeLoc());
1083}
1084
1085bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1086 return Visit(TL.getPointeeLoc());
1087}
1088
1089bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1090 return Visit(TL.getPointeeLoc());
1091}
1092
1093bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001094 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001095}
1096
1097bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001098 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001099}
1100
Douglas Gregor01829d32010-08-31 14:41:23 +00001101bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1102 bool SkipResultType) {
1103 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001104 return true;
1105
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001106 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001107 if (Decl *D = TL.getArg(I))
1108 if (Visit(MakeCXCursor(D, TU)))
1109 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001110
1111 return false;
1112}
1113
1114bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1115 if (Visit(TL.getElementLoc()))
1116 return true;
1117
1118 if (Expr *Size = TL.getSizeExpr())
1119 return Visit(MakeCXCursor(Size, StmtParent, TU));
1120
1121 return false;
1122}
1123
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001124bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1125 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001126 // Visit the template name.
1127 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1128 TL.getTemplateNameLoc()))
1129 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001130
1131 // Visit the template arguments.
1132 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1133 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1134 return true;
1135
1136 return false;
1137}
1138
Douglas Gregor2332c112010-01-21 20:48:56 +00001139bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1140 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1141}
1142
1143bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1144 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1145 return Visit(TSInfo->getTypeLoc());
1146
1147 return false;
1148}
1149
Douglas Gregora59e3902010-01-21 23:27:09 +00001150bool CursorVisitor::VisitStmt(Stmt *S) {
1151 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1152 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001153 if (Stmt *C = *Child)
1154 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1155 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001156 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001157
Douglas Gregora59e3902010-01-21 23:27:09 +00001158 return false;
1159}
1160
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001161bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1162 // Specially handle CaseStmts because they can be nested, e.g.:
1163 //
1164 // case 1:
1165 // case 2:
1166 //
1167 // In this case the second CaseStmt is the child of the first. Walking
1168 // these recursively can blow out the stack.
1169 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1170 while (true) {
1171 // Set the Parent field to Cursor, then back to its old value once we're
1172 // done.
1173 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1174
1175 if (Stmt *LHS = S->getLHS())
1176 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1177 return true;
1178 if (Stmt *RHS = S->getRHS())
1179 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1180 return true;
1181 if (Stmt *SubStmt = S->getSubStmt()) {
1182 if (!isa<CaseStmt>(SubStmt))
1183 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1184
1185 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1186 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1187 Cursor = MakeCXCursor(CS, StmtParent, TU);
1188 if (RegionOfInterest.isValid()) {
1189 SourceRange Range = CS->getSourceRange();
1190 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1191 return false;
1192 }
1193
1194 switch (Visitor(Cursor, Parent, ClientData)) {
1195 case CXChildVisit_Break: return true;
1196 case CXChildVisit_Continue: return false;
1197 case CXChildVisit_Recurse:
1198 // Perform tail-recursion manually.
1199 S = CS;
1200 continue;
1201 }
1202 }
1203 return false;
1204 }
1205}
1206
Douglas Gregora59e3902010-01-21 23:27:09 +00001207bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1208 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1209 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001210 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001211 return true;
1212 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001213
Douglas Gregora59e3902010-01-21 23:27:09 +00001214 return false;
1215}
1216
Douglas Gregorf5bab412010-01-22 01:00:11 +00001217bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1218 if (VarDecl *Var = S->getConditionVariable()) {
1219 if (Visit(MakeCXCursor(Var, TU)))
1220 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001221 }
1222
Douglas Gregor263b47b2010-01-25 16:12:32 +00001223 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1224 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001225 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1226 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001227 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1228 return true;
1229
1230 return false;
1231}
1232
1233bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1234 if (VarDecl *Var = S->getConditionVariable()) {
1235 if (Visit(MakeCXCursor(Var, TU)))
1236 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001237 }
1238
Douglas Gregor263b47b2010-01-25 16:12:32 +00001239 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1240 return true;
1241 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1242 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001243
Douglas Gregor263b47b2010-01-25 16:12:32 +00001244 return false;
1245}
1246
1247bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1248 if (VarDecl *Var = S->getConditionVariable()) {
1249 if (Visit(MakeCXCursor(Var, TU)))
1250 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001251 }
1252
Douglas Gregor263b47b2010-01-25 16:12:32 +00001253 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1254 return true;
1255 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001256 return true;
1257
Douglas Gregor263b47b2010-01-25 16:12:32 +00001258 return false;
1259}
1260
1261bool CursorVisitor::VisitForStmt(ForStmt *S) {
1262 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1263 return true;
1264 if (VarDecl *Var = S->getConditionVariable()) {
1265 if (Visit(MakeCXCursor(Var, TU)))
1266 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001267 }
1268
Douglas Gregor263b47b2010-01-25 16:12:32 +00001269 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1270 return true;
1271 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1272 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001273 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1274 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001275
Douglas Gregorf5bab412010-01-22 01:00:11 +00001276 return false;
1277}
1278
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001279bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1280 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1281 return true;
1282
1283 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1284 return true;
1285
1286 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1287 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1288 return true;
1289
1290 return false;
1291}
1292
Ted Kremenek3064ef92010-08-27 21:34:58 +00001293bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1294 if (D->isDefinition()) {
1295 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1296 E = D->bases_end(); I != E; ++I) {
1297 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1298 return true;
1299 }
1300 }
1301
1302 return VisitTagDecl(D);
1303}
1304
1305
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001306bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1307 return Visit(B->getBlockDecl());
1308}
1309
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001310bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1311 // FIXME: Visit fields as well?
1312 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1313 return true;
1314
1315 return VisitExpr(E);
1316}
1317
Douglas Gregor336fd812010-01-23 00:40:08 +00001318bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1319 if (E->isArgumentType()) {
1320 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1321 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001322
Douglas Gregor336fd812010-01-23 00:40:08 +00001323 return false;
1324 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001325
Douglas Gregor336fd812010-01-23 00:40:08 +00001326 return VisitExpr(E);
1327}
1328
1329bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1330 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1331 if (Visit(TSInfo->getTypeLoc()))
1332 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001333
Douglas Gregor336fd812010-01-23 00:40:08 +00001334 return VisitCastExpr(E);
1335}
1336
1337bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1338 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1339 if (Visit(TSInfo->getTypeLoc()))
1340 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001341
Douglas Gregor336fd812010-01-23 00:40:08 +00001342 return VisitExpr(E);
1343}
1344
Douglas Gregor648220e2010-08-10 15:02:34 +00001345bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1346 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1347 Visit(E->getArgTInfo2()->getTypeLoc());
1348}
1349
1350bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1351 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1352 return true;
1353
1354 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1355}
1356
Douglas Gregorc2350e52010-03-08 16:40:19 +00001357bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001358 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1359 if (Visit(TSInfo->getTypeLoc()))
1360 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001361
1362 return VisitExpr(E);
1363}
1364
Douglas Gregor81d34662010-04-20 15:39:42 +00001365bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1366 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1367}
1368
1369
Ted Kremenek09dfa372010-02-18 05:46:33 +00001370bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001371 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1372 i != e; ++i)
1373 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001374 return true;
1375
1376 return false;
1377}
1378
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001379extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001380CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1381 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001382 // We use crash recovery to make some of our APIs more reliable, implicitly
1383 // enable it.
1384 llvm::CrashRecoveryContext::Enable();
1385
Douglas Gregora030b7c2010-01-22 20:35:53 +00001386 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001387 if (excludeDeclarationsFromPCH)
1388 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001389 if (displayDiagnostics)
1390 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001391 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001392}
1393
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001394void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001395 if (CIdx)
1396 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001397 if (getenv("LIBCLANG_TIMING"))
1398 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001399}
1400
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001401void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001402 if (CIdx) {
1403 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1404 CXXIdx->setUseExternalASTGeneration(value);
1405 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001406}
1407
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001408CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001409 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001410 if (!CIdx)
1411 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001412
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001413 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001414
Douglas Gregor28019772010-04-05 23:52:57 +00001415 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001416 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001417 CXXIdx->getOnlyLocalDecls(),
1418 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001419}
1420
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001421unsigned clang_defaultEditingTranslationUnitOptions() {
1422 return CXTranslationUnit_PrecompiledPreamble;
1423}
1424
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001425CXTranslationUnit
1426clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1427 const char *source_filename,
1428 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001429 const char **command_line_args,
1430 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001431 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001432 return clang_parseTranslationUnit(CIdx, source_filename,
1433 command_line_args, num_command_line_args,
1434 unsaved_files, num_unsaved_files,
1435 CXTranslationUnit_DetailedPreprocessingRecord);
1436}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001437
1438struct ParseTranslationUnitInfo {
1439 CXIndex CIdx;
1440 const char *source_filename;
1441 const char **command_line_args;
1442 int num_command_line_args;
1443 struct CXUnsavedFile *unsaved_files;
1444 unsigned num_unsaved_files;
1445 unsigned options;
1446 CXTranslationUnit result;
1447};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001448static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001449 ParseTranslationUnitInfo *PTUI =
1450 static_cast<ParseTranslationUnitInfo*>(UserData);
1451 CXIndex CIdx = PTUI->CIdx;
1452 const char *source_filename = PTUI->source_filename;
1453 const char **command_line_args = PTUI->command_line_args;
1454 int num_command_line_args = PTUI->num_command_line_args;
1455 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1456 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1457 unsigned options = PTUI->options;
1458 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001459
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001460 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001461 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001462
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001463 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1464
Douglas Gregor44c181a2010-07-23 00:33:23 +00001465 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001466 bool CompleteTranslationUnit
1467 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001468 bool CacheCodeCompetionResults
1469 = options & CXTranslationUnit_CacheCompletionResults;
1470
Douglas Gregor5352ac02010-01-28 00:27:43 +00001471 // Configure the diagnostics.
1472 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001473 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1474 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001475
Douglas Gregor4db64a42010-01-23 00:14:00 +00001476 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1477 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001478 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001479 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001480 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001481 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1482 Buffer));
1483 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001484
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001485 if (!CXXIdx->getUseExternalASTGeneration()) {
1486 llvm::SmallVector<const char *, 16> Args;
1487
1488 // The 'source_filename' argument is optional. If the caller does not
1489 // specify it then it is assumed that the source file is specified
1490 // in the actual argument list.
1491 if (source_filename)
1492 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001493
1494 // Since the Clang C library is primarily used by batch tools dealing with
1495 // (often very broken) source code, where spell-checking can have a
1496 // significant negative impact on performance (particularly when
1497 // precompiled headers are involved), we disable it by default.
1498 // Note that we place this argument early in the list, so that it can be
1499 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001500 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001501
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001502 Args.insert(Args.end(), command_line_args,
1503 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001504
Douglas Gregor44c181a2010-07-23 00:33:23 +00001505 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001506 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1507 Args.push_back("-Xclang");
1508 Args.push_back("-detailed-preprocessing-record");
1509 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001510
Douglas Gregor5352ac02010-01-28 00:27:43 +00001511 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001512
Ted Kremenek29b72842010-01-07 22:49:05 +00001513#ifdef USE_CRASHTRACER
1514 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001515#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001516
Daniel Dunbar94220972009-12-05 02:17:18 +00001517 llvm::OwningPtr<ASTUnit> Unit(
1518 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001519 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001520 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001521 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001522 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001523 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001524 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001525 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001526 CompleteTranslationUnit,
1527 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001528
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001529 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001530 // Make sure to check that 'Unit' is non-NULL.
1531 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001532 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1533 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001534 D != DEnd; ++D) {
1535 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001536 CXString Msg = clang_formatDiagnostic(&Diag,
1537 clang_defaultDiagnosticDisplayOptions());
1538 fprintf(stderr, "%s\n", clang_getCString(Msg));
1539 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001540 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001541#ifdef LLVM_ON_WIN32
1542 // On Windows, force a flush, since there may be multiple copies of
1543 // stderr and stdout in the file system, all with different buffers
1544 // but writing to the same device.
1545 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001546#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001547 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001548 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001549
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001550 PTUI->result = Unit.take();
1551 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001552 }
1553
Ted Kremenek139ba862009-10-22 00:03:57 +00001554 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001555 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001556
Ted Kremenek139ba862009-10-22 00:03:57 +00001557 // First add the complete path to the 'clang' executable.
1558 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001559 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001560
Ted Kremenek139ba862009-10-22 00:03:57 +00001561 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001562 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001563
Ted Kremenek139ba862009-10-22 00:03:57 +00001564 // The 'source_filename' argument is optional. If the caller does not
1565 // specify it then it is assumed that the source file is specified
1566 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001567 if (source_filename)
1568 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001569
Steve Naroff37b5ac22009-10-15 20:50:09 +00001570 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001571 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001572 char astTmpFile[L_tmpnam];
1573 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001574
1575 // Since the Clang C library is primarily used by batch tools dealing with
1576 // (often very broken) source code, where spell-checking can have a
1577 // significant negative impact on performance (particularly when
1578 // precompiled headers are involved), we disable it by default.
1579 // Note that we place this argument early in the list, so that it can be
1580 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001581 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001582
Douglas Gregor4db64a42010-01-23 00:14:00 +00001583 // Remap any unsaved files to temporary files.
1584 std::vector<llvm::sys::Path> TemporaryFiles;
1585 std::vector<std::string> RemapArgs;
1586 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001587 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001588
Douglas Gregor4db64a42010-01-23 00:14:00 +00001589 // The pointers into the elements of RemapArgs are stable because we
1590 // won't be adding anything to RemapArgs after this point.
1591 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1592 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001593
Ted Kremenek139ba862009-10-22 00:03:57 +00001594 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1595 for (int i = 0; i < num_command_line_args; ++i)
1596 if (const char *arg = command_line_args[i]) {
1597 if (strcmp(arg, "-o") == 0) {
1598 ++i; // Also skip the matching argument.
1599 continue;
1600 }
1601 if (strcmp(arg, "-emit-ast") == 0 ||
1602 strcmp(arg, "-c") == 0 ||
1603 strcmp(arg, "-fsyntax-only") == 0) {
1604 continue;
1605 }
1606
1607 // Keep the argument.
1608 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001609 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001610
Douglas Gregord93256e2010-01-28 06:00:51 +00001611 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001612 char tmpFileResults[L_tmpnam];
1613 char *tmpResultsFileName = tmpnam(tmpFileResults);
1614 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001615 TemporaryFiles.push_back(DiagnosticsFile);
1616 argv.push_back("-fdiagnostics-binary");
1617
Douglas Gregor44c181a2010-07-23 00:33:23 +00001618 // Do we need the detailed preprocessing record?
1619 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1620 argv.push_back("-Xclang");
1621 argv.push_back("-detailed-preprocessing-record");
1622 }
1623
Ted Kremenek139ba862009-10-22 00:03:57 +00001624 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001625 argv.push_back(NULL);
1626
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001627 // Invoke 'clang'.
1628 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1629 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001630 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001631 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1632 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001633 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001634 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001635 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001636
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001637 if (!ErrMsg.empty()) {
1638 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001639 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001640 I != E; ++I) {
1641 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001642 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001643 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001644 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001645
Daniel Dunbar32141c82010-02-23 20:23:45 +00001646 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001647 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001648
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001649 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001650 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001651 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001652 RemappedFiles.size(),
1653 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001654 if (ATU) {
1655 LoadSerializedDiagnostics(DiagnosticsFile,
1656 num_unsaved_files, unsaved_files,
1657 ATU->getFileManager(),
1658 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001659 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001660 } else if (CXXIdx->getDisplayDiagnostics()) {
1661 // We failed to load the ASTUnit, but we can still deserialize the
1662 // diagnostics and emit them.
1663 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001664 Diagnostic Diag;
1665 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001666 // FIXME: Faked LangOpts!
1667 LangOptions LangOpts;
1668 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1669 LoadSerializedDiagnostics(DiagnosticsFile,
1670 num_unsaved_files, unsaved_files,
1671 FileMgr, SourceMgr, Diags);
1672 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1673 DEnd = Diags.end();
1674 D != DEnd; ++D) {
1675 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001676 CXString Msg = clang_formatDiagnostic(&Diag,
1677 clang_defaultDiagnosticDisplayOptions());
1678 fprintf(stderr, "%s\n", clang_getCString(Msg));
1679 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001680 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001681
1682#ifdef LLVM_ON_WIN32
1683 // On Windows, force a flush, since there may be multiple copies of
1684 // stderr and stdout in the file system, all with different buffers
1685 // but writing to the same device.
1686 fflush(stderr);
1687#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001688 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001689
Douglas Gregor313e26c2010-02-18 23:35:40 +00001690 if (ATU) {
1691 // Make the translation unit responsible for destroying all temporary files.
1692 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1693 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001694 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001695 } else {
1696 // Destroy all of the temporary files now; they can't be referenced any
1697 // longer.
1698 llvm::sys::Path(astTmpFile).eraseFromDisk();
1699 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1700 TemporaryFiles[i].eraseFromDisk();
1701 }
1702
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001703 PTUI->result = ATU;
1704}
1705CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1706 const char *source_filename,
1707 const char **command_line_args,
1708 int num_command_line_args,
1709 struct CXUnsavedFile *unsaved_files,
1710 unsigned num_unsaved_files,
1711 unsigned options) {
1712 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1713 num_command_line_args, unsaved_files, num_unsaved_files,
1714 options, 0 };
1715 llvm::CrashRecoveryContext CRC;
1716
1717 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001718 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1719 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1720 fprintf(stderr, " 'command_line_args' : [");
1721 for (int i = 0; i != num_command_line_args; ++i) {
1722 if (i)
1723 fprintf(stderr, ", ");
1724 fprintf(stderr, "'%s'", command_line_args[i]);
1725 }
1726 fprintf(stderr, "],\n");
1727 fprintf(stderr, " 'unsaved_files' : [");
1728 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1729 if (i)
1730 fprintf(stderr, ", ");
1731 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1732 unsaved_files[i].Length);
1733 }
1734 fprintf(stderr, "],\n");
1735 fprintf(stderr, " 'options' : %d,\n", options);
1736 fprintf(stderr, "}\n");
1737
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001738 return 0;
1739 }
1740
1741 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001742}
1743
Douglas Gregor19998442010-08-13 15:35:05 +00001744unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1745 return CXSaveTranslationUnit_None;
1746}
1747
1748int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1749 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001750 if (!TU)
1751 return 1;
1752
1753 return static_cast<ASTUnit *>(TU)->Save(FileName);
1754}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001755
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001756void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001757 if (CTUnit) {
1758 // If the translation unit has been marked as unsafe to free, just discard
1759 // it.
1760 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1761 return;
1762
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001763 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001764 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001765}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001766
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001767unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1768 return CXReparse_None;
1769}
1770
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001771struct ReparseTranslationUnitInfo {
1772 CXTranslationUnit TU;
1773 unsigned num_unsaved_files;
1774 struct CXUnsavedFile *unsaved_files;
1775 unsigned options;
1776 int result;
1777};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001778static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001779 ReparseTranslationUnitInfo *RTUI =
1780 static_cast<ReparseTranslationUnitInfo*>(UserData);
1781 CXTranslationUnit TU = RTUI->TU;
1782 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1783 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1784 unsigned options = RTUI->options;
1785 (void) options;
1786 RTUI->result = 1;
1787
Douglas Gregorabc563f2010-07-19 21:46:24 +00001788 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001789 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001790
1791 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1792 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1793 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1794 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001795 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001796 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1797 Buffer));
1798 }
1799
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001800 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1801 RemappedFiles.size()))
1802 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001803}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001804int clang_reparseTranslationUnit(CXTranslationUnit TU,
1805 unsigned num_unsaved_files,
1806 struct CXUnsavedFile *unsaved_files,
1807 unsigned options) {
1808 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1809 options, 0 };
1810 llvm::CrashRecoveryContext CRC;
1811
1812 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001813 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001814 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1815 return 1;
1816 }
1817
1818 return RTUI.result;
1819}
1820
Douglas Gregordf95a132010-08-09 20:45:32 +00001821
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001822CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001823 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001824 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001825
Steve Naroff77accc12009-09-03 18:19:54 +00001826 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001827 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001828}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001829
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001830CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001831 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001832 return Result;
1833}
1834
Ted Kremenekfb480492010-01-13 21:46:36 +00001835} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001836
Ted Kremenekfb480492010-01-13 21:46:36 +00001837//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001838// CXSourceLocation and CXSourceRange Operations.
1839//===----------------------------------------------------------------------===//
1840
Douglas Gregorb9790342010-01-22 21:44:22 +00001841extern "C" {
1842CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001843 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001844 return Result;
1845}
1846
1847unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001848 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1849 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1850 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001851}
1852
1853CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1854 CXFile file,
1855 unsigned line,
1856 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001857 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001858 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001859
Douglas Gregorb9790342010-01-22 21:44:22 +00001860 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1861 SourceLocation SLoc
1862 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001863 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001864 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001865
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001866 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001867}
1868
Douglas Gregor5352ac02010-01-28 00:27:43 +00001869CXSourceRange clang_getNullRange() {
1870 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1871 return Result;
1872}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001873
Douglas Gregor5352ac02010-01-28 00:27:43 +00001874CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1875 if (begin.ptr_data[0] != end.ptr_data[0] ||
1876 begin.ptr_data[1] != end.ptr_data[1])
1877 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001878
1879 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001880 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001881 return Result;
1882}
1883
Douglas Gregor46766dc2010-01-26 19:19:08 +00001884void clang_getInstantiationLocation(CXSourceLocation location,
1885 CXFile *file,
1886 unsigned *line,
1887 unsigned *column,
1888 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001889 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1890
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001891 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001892 if (file)
1893 *file = 0;
1894 if (line)
1895 *line = 0;
1896 if (column)
1897 *column = 0;
1898 if (offset)
1899 *offset = 0;
1900 return;
1901 }
1902
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001903 const SourceManager &SM =
1904 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001905 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001906
1907 if (file)
1908 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1909 if (line)
1910 *line = SM.getInstantiationLineNumber(InstLoc);
1911 if (column)
1912 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001913 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001914 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001915}
1916
Douglas Gregor1db19de2010-01-19 21:36:55 +00001917CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001918 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001919 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001920 return Result;
1921}
1922
1923CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001924 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001925 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001926 return Result;
1927}
1928
Douglas Gregorb9790342010-01-22 21:44:22 +00001929} // end: extern "C"
1930
Douglas Gregor1db19de2010-01-19 21:36:55 +00001931//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001932// CXFile Operations.
1933//===----------------------------------------------------------------------===//
1934
1935extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001936CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001937 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001938 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001939
Steve Naroff88145032009-10-27 14:35:18 +00001940 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001941 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001942}
1943
1944time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001945 if (!SFile)
1946 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001947
Steve Naroff88145032009-10-27 14:35:18 +00001948 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1949 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001950}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001951
Douglas Gregorb9790342010-01-22 21:44:22 +00001952CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1953 if (!tu)
1954 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001955
Douglas Gregorb9790342010-01-22 21:44:22 +00001956 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001957
Douglas Gregorb9790342010-01-22 21:44:22 +00001958 FileManager &FMgr = CXXUnit->getFileManager();
1959 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1960 return const_cast<FileEntry *>(File);
1961}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001962
Ted Kremenekfb480492010-01-13 21:46:36 +00001963} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001964
Ted Kremenekfb480492010-01-13 21:46:36 +00001965//===----------------------------------------------------------------------===//
1966// CXCursor Operations.
1967//===----------------------------------------------------------------------===//
1968
Ted Kremenekfb480492010-01-13 21:46:36 +00001969static Decl *getDeclFromExpr(Stmt *E) {
1970 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1971 return RefExpr->getDecl();
1972 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1973 return ME->getMemberDecl();
1974 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1975 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001976
Ted Kremenekfb480492010-01-13 21:46:36 +00001977 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1978 return getDeclFromExpr(CE->getCallee());
1979 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1980 return getDeclFromExpr(CE->getSubExpr());
1981 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1982 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001983
Ted Kremenekfb480492010-01-13 21:46:36 +00001984 return 0;
1985}
1986
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001987static SourceLocation getLocationFromExpr(Expr *E) {
1988 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1989 return /*FIXME:*/Msg->getLeftLoc();
1990 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1991 return DRE->getLocation();
1992 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1993 return Member->getMemberLoc();
1994 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1995 return Ivar->getLocation();
1996 return E->getLocStart();
1997}
1998
Ted Kremenekfb480492010-01-13 21:46:36 +00001999extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002000
2001unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002002 CXCursorVisitor visitor,
2003 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002004 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002005
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002006 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2007 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002008 return CursorVis.VisitChildren(parent);
2009}
2010
Douglas Gregor78205d42010-01-20 21:45:58 +00002011static CXString getDeclSpelling(Decl *D) {
2012 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2013 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002014 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002015
Douglas Gregor78205d42010-01-20 21:45:58 +00002016 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002017 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002018
Douglas Gregor78205d42010-01-20 21:45:58 +00002019 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2020 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2021 // and returns different names. NamedDecl returns the class name and
2022 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002023 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002024
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002025 llvm::SmallString<1024> S;
2026 llvm::raw_svector_ostream os(S);
2027 ND->printName(os);
2028
2029 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002030}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002031
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002032CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002033 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002034 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002035
Steve Narofff334b4e2009-09-02 18:26:48 +00002036 if (clang_isReference(C.kind)) {
2037 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002038 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002039 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002040 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002041 }
2042 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002043 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002044 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002045 }
2046 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002047 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002048 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002049 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002050 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002051 case CXCursor_CXXBaseSpecifier: {
2052 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2053 return createCXString(B->getType().getAsString());
2054 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002055 case CXCursor_TypeRef: {
2056 TypeDecl *Type = getCursorTypeRef(C).first;
2057 assert(Type && "Missing type decl");
2058
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002059 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2060 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002061 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002062 case CXCursor_TemplateRef: {
2063 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002064 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002065
2066 return createCXString(Template->getNameAsString());
2067 }
Douglas Gregor69319002010-08-31 23:48:11 +00002068
2069 case CXCursor_NamespaceRef: {
2070 NamedDecl *NS = getCursorNamespaceRef(C).first;
2071 assert(NS && "Missing namespace decl");
2072
2073 return createCXString(NS->getNameAsString());
2074 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002075
Daniel Dunbaracca7252009-11-30 20:42:49 +00002076 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002077 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002078 }
2079 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002080
2081 if (clang_isExpression(C.kind)) {
2082 Decl *D = getDeclFromExpr(getCursorExpr(C));
2083 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002084 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002085 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002086 }
2087
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002088 if (C.kind == CXCursor_MacroInstantiation)
2089 return createCXString(getCursorMacroInstantiation(C)->getName()
2090 ->getNameStart());
2091
Douglas Gregor572feb22010-03-18 18:04:21 +00002092 if (C.kind == CXCursor_MacroDefinition)
2093 return createCXString(getCursorMacroDefinition(C)->getName()
2094 ->getNameStart());
2095
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002096 if (clang_isDeclaration(C.kind))
2097 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002098
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002099 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002100}
2101
Ted Kremeneke68fff62010-02-17 00:41:32 +00002102CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002103 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002104 case CXCursor_FunctionDecl:
2105 return createCXString("FunctionDecl");
2106 case CXCursor_TypedefDecl:
2107 return createCXString("TypedefDecl");
2108 case CXCursor_EnumDecl:
2109 return createCXString("EnumDecl");
2110 case CXCursor_EnumConstantDecl:
2111 return createCXString("EnumConstantDecl");
2112 case CXCursor_StructDecl:
2113 return createCXString("StructDecl");
2114 case CXCursor_UnionDecl:
2115 return createCXString("UnionDecl");
2116 case CXCursor_ClassDecl:
2117 return createCXString("ClassDecl");
2118 case CXCursor_FieldDecl:
2119 return createCXString("FieldDecl");
2120 case CXCursor_VarDecl:
2121 return createCXString("VarDecl");
2122 case CXCursor_ParmDecl:
2123 return createCXString("ParmDecl");
2124 case CXCursor_ObjCInterfaceDecl:
2125 return createCXString("ObjCInterfaceDecl");
2126 case CXCursor_ObjCCategoryDecl:
2127 return createCXString("ObjCCategoryDecl");
2128 case CXCursor_ObjCProtocolDecl:
2129 return createCXString("ObjCProtocolDecl");
2130 case CXCursor_ObjCPropertyDecl:
2131 return createCXString("ObjCPropertyDecl");
2132 case CXCursor_ObjCIvarDecl:
2133 return createCXString("ObjCIvarDecl");
2134 case CXCursor_ObjCInstanceMethodDecl:
2135 return createCXString("ObjCInstanceMethodDecl");
2136 case CXCursor_ObjCClassMethodDecl:
2137 return createCXString("ObjCClassMethodDecl");
2138 case CXCursor_ObjCImplementationDecl:
2139 return createCXString("ObjCImplementationDecl");
2140 case CXCursor_ObjCCategoryImplDecl:
2141 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002142 case CXCursor_CXXMethod:
2143 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002144 case CXCursor_UnexposedDecl:
2145 return createCXString("UnexposedDecl");
2146 case CXCursor_ObjCSuperClassRef:
2147 return createCXString("ObjCSuperClassRef");
2148 case CXCursor_ObjCProtocolRef:
2149 return createCXString("ObjCProtocolRef");
2150 case CXCursor_ObjCClassRef:
2151 return createCXString("ObjCClassRef");
2152 case CXCursor_TypeRef:
2153 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002154 case CXCursor_TemplateRef:
2155 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002156 case CXCursor_NamespaceRef:
2157 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002158 case CXCursor_UnexposedExpr:
2159 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002160 case CXCursor_BlockExpr:
2161 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002162 case CXCursor_DeclRefExpr:
2163 return createCXString("DeclRefExpr");
2164 case CXCursor_MemberRefExpr:
2165 return createCXString("MemberRefExpr");
2166 case CXCursor_CallExpr:
2167 return createCXString("CallExpr");
2168 case CXCursor_ObjCMessageExpr:
2169 return createCXString("ObjCMessageExpr");
2170 case CXCursor_UnexposedStmt:
2171 return createCXString("UnexposedStmt");
2172 case CXCursor_InvalidFile:
2173 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002174 case CXCursor_InvalidCode:
2175 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002176 case CXCursor_NoDeclFound:
2177 return createCXString("NoDeclFound");
2178 case CXCursor_NotImplemented:
2179 return createCXString("NotImplemented");
2180 case CXCursor_TranslationUnit:
2181 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002182 case CXCursor_UnexposedAttr:
2183 return createCXString("UnexposedAttr");
2184 case CXCursor_IBActionAttr:
2185 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002186 case CXCursor_IBOutletAttr:
2187 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002188 case CXCursor_IBOutletCollectionAttr:
2189 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002190 case CXCursor_PreprocessingDirective:
2191 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002192 case CXCursor_MacroDefinition:
2193 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002194 case CXCursor_MacroInstantiation:
2195 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002196 case CXCursor_Namespace:
2197 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002198 case CXCursor_LinkageSpec:
2199 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002200 case CXCursor_CXXBaseSpecifier:
2201 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002202 case CXCursor_Constructor:
2203 return createCXString("CXXConstructor");
2204 case CXCursor_Destructor:
2205 return createCXString("CXXDestructor");
2206 case CXCursor_ConversionFunction:
2207 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002208 case CXCursor_TemplateTypeParameter:
2209 return createCXString("TemplateTypeParameter");
2210 case CXCursor_NonTypeTemplateParameter:
2211 return createCXString("NonTypeTemplateParameter");
2212 case CXCursor_TemplateTemplateParameter:
2213 return createCXString("TemplateTemplateParameter");
2214 case CXCursor_FunctionTemplate:
2215 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002216 case CXCursor_ClassTemplate:
2217 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002218 case CXCursor_ClassTemplatePartialSpecialization:
2219 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002220 case CXCursor_NamespaceAlias:
2221 return createCXString("NamespaceAlias");
Steve Naroff89922f82009-08-31 00:59:03 +00002222 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002223
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002224 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002225 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002226}
Steve Naroff89922f82009-08-31 00:59:03 +00002227
Ted Kremeneke68fff62010-02-17 00:41:32 +00002228enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2229 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002230 CXClientData client_data) {
2231 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2232 *BestCursor = cursor;
2233 return CXChildVisit_Recurse;
2234}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002235
Douglas Gregorb9790342010-01-22 21:44:22 +00002236CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2237 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002238 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002239
Douglas Gregorb9790342010-01-22 21:44:22 +00002240 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002241 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2242
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002243 // Translate the given source location to make it point at the beginning of
2244 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002245 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002246
2247 // Guard against an invalid SourceLocation, or we may assert in one
2248 // of the following calls.
2249 if (SLoc.isInvalid())
2250 return clang_getNullCursor();
2251
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002252 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2253 CXXUnit->getASTContext().getLangOptions());
2254
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002255 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2256 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002257 // FIXME: Would be great to have a "hint" cursor, then walk from that
2258 // hint cursor upward until we find a cursor whose source range encloses
2259 // the region of interest, rather than starting from the translation unit.
2260 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002261 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002262 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002263 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002264 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002265 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002266}
2267
Ted Kremenek73885552009-11-17 19:28:59 +00002268CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002269 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002270}
2271
2272unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002273 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002274}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002275
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002276unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002277 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2278}
2279
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002280unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002281 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2282}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002283
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002284unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002285 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2286}
2287
Douglas Gregor97b98722010-01-19 23:20:36 +00002288unsigned clang_isExpression(enum CXCursorKind K) {
2289 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2290}
2291
2292unsigned clang_isStatement(enum CXCursorKind K) {
2293 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2294}
2295
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002296unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2297 return K == CXCursor_TranslationUnit;
2298}
2299
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002300unsigned clang_isPreprocessing(enum CXCursorKind K) {
2301 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2302}
2303
Ted Kremenekad6eff62010-03-08 21:17:29 +00002304unsigned clang_isUnexposed(enum CXCursorKind K) {
2305 switch (K) {
2306 case CXCursor_UnexposedDecl:
2307 case CXCursor_UnexposedExpr:
2308 case CXCursor_UnexposedStmt:
2309 case CXCursor_UnexposedAttr:
2310 return true;
2311 default:
2312 return false;
2313 }
2314}
2315
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002316CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002317 return C.kind;
2318}
2319
Douglas Gregor98258af2010-01-18 22:46:11 +00002320CXSourceLocation clang_getCursorLocation(CXCursor C) {
2321 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002322 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002323 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002324 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2325 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002326 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002327 }
2328
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002329 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002330 std::pair<ObjCProtocolDecl *, SourceLocation> P
2331 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002332 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002333 }
2334
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002335 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002336 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2337 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002338 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002339 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002340
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002341 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002342 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002343 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002344 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002345
2346 case CXCursor_TemplateRef: {
2347 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2348 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2349 }
2350
Douglas Gregor69319002010-08-31 23:48:11 +00002351 case CXCursor_NamespaceRef: {
2352 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2353 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2354 }
2355
Ted Kremenek3064ef92010-08-27 21:34:58 +00002356 case CXCursor_CXXBaseSpecifier: {
2357 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2358 return clang_getNullLocation();
2359 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002360
Douglas Gregorf46034a2010-01-18 23:41:10 +00002361 default:
2362 // FIXME: Need a way to enumerate all non-reference cases.
2363 llvm_unreachable("Missed a reference kind");
2364 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002365 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002366
2367 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002368 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002369 getLocationFromExpr(getCursorExpr(C)));
2370
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002371 if (C.kind == CXCursor_PreprocessingDirective) {
2372 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2373 return cxloc::translateSourceLocation(getCursorContext(C), L);
2374 }
Douglas Gregor48072312010-03-18 15:23:44 +00002375
2376 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002377 SourceLocation L
2378 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002379 return cxloc::translateSourceLocation(getCursorContext(C), L);
2380 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002381
2382 if (C.kind == CXCursor_MacroDefinition) {
2383 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2384 return cxloc::translateSourceLocation(getCursorContext(C), L);
2385 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002386
Ted Kremenek9a700d22010-05-12 06:16:13 +00002387 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002388 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002389
Douglas Gregorf46034a2010-01-18 23:41:10 +00002390 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002391 SourceLocation Loc = D->getLocation();
2392 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2393 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002394 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002395}
Douglas Gregora7bde202010-01-19 00:34:46 +00002396
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002397} // end extern "C"
2398
2399static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002400 if (clang_isReference(C.kind)) {
2401 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002402 case CXCursor_ObjCSuperClassRef:
2403 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002404
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002405 case CXCursor_ObjCProtocolRef:
2406 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002407
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002408 case CXCursor_ObjCClassRef:
2409 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002410
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002411 case CXCursor_TypeRef:
2412 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002413
2414 case CXCursor_TemplateRef:
2415 return getCursorTemplateRef(C).second;
2416
Douglas Gregor69319002010-08-31 23:48:11 +00002417 case CXCursor_NamespaceRef:
2418 return getCursorNamespaceRef(C).second;
2419
Ted Kremenek3064ef92010-08-27 21:34:58 +00002420 case CXCursor_CXXBaseSpecifier:
2421 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2422 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002423
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002424 default:
2425 // FIXME: Need a way to enumerate all non-reference cases.
2426 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002427 }
2428 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002429
2430 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002431 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002432
2433 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002434 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002435
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002436 if (C.kind == CXCursor_PreprocessingDirective)
2437 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002438
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002439 if (C.kind == CXCursor_MacroInstantiation)
2440 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002441
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002442 if (C.kind == CXCursor_MacroDefinition)
2443 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002444
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002445 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2446 return getCursorDecl(C)->getSourceRange();
2447
2448 return SourceRange();
2449}
2450
2451extern "C" {
2452
2453CXSourceRange clang_getCursorExtent(CXCursor C) {
2454 SourceRange R = getRawCursorExtent(C);
2455 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002456 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002457
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002458 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002459}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002460
2461CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002462 if (clang_isInvalid(C.kind))
2463 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002464
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002465 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002466 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002467 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002468
Douglas Gregor97b98722010-01-19 23:20:36 +00002469 if (clang_isExpression(C.kind)) {
2470 Decl *D = getDeclFromExpr(getCursorExpr(C));
2471 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002472 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002473 return clang_getNullCursor();
2474 }
2475
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002476 if (C.kind == CXCursor_MacroInstantiation) {
2477 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2478 return MakeMacroDefinitionCursor(Def, CXXUnit);
2479 }
2480
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002481 if (!clang_isReference(C.kind))
2482 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002483
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002484 switch (C.kind) {
2485 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002486 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002487
2488 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002489 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002490
2491 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002492 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002493
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002494 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002495 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002496
2497 case CXCursor_TemplateRef:
2498 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2499
Douglas Gregor69319002010-08-31 23:48:11 +00002500 case CXCursor_NamespaceRef:
2501 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2502
Ted Kremenek3064ef92010-08-27 21:34:58 +00002503 case CXCursor_CXXBaseSpecifier: {
2504 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2505 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2506 CXXUnit));
2507 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002508
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002509 default:
2510 // We would prefer to enumerate all non-reference cursor kinds here.
2511 llvm_unreachable("Unhandled reference cursor kind");
2512 break;
2513 }
2514 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002515
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002516 return clang_getNullCursor();
2517}
2518
Douglas Gregorb6998662010-01-19 19:34:47 +00002519CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002520 if (clang_isInvalid(C.kind))
2521 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002522
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002523 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002524
Douglas Gregorb6998662010-01-19 19:34:47 +00002525 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002526 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002527 C = clang_getCursorReferenced(C);
2528 WasReference = true;
2529 }
2530
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002531 if (C.kind == CXCursor_MacroInstantiation)
2532 return clang_getCursorReferenced(C);
2533
Douglas Gregorb6998662010-01-19 19:34:47 +00002534 if (!clang_isDeclaration(C.kind))
2535 return clang_getNullCursor();
2536
2537 Decl *D = getCursorDecl(C);
2538 if (!D)
2539 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002540
Douglas Gregorb6998662010-01-19 19:34:47 +00002541 switch (D->getKind()) {
2542 // Declaration kinds that don't really separate the notions of
2543 // declaration and definition.
2544 case Decl::Namespace:
2545 case Decl::Typedef:
2546 case Decl::TemplateTypeParm:
2547 case Decl::EnumConstant:
2548 case Decl::Field:
2549 case Decl::ObjCIvar:
2550 case Decl::ObjCAtDefsField:
2551 case Decl::ImplicitParam:
2552 case Decl::ParmVar:
2553 case Decl::NonTypeTemplateParm:
2554 case Decl::TemplateTemplateParm:
2555 case Decl::ObjCCategoryImpl:
2556 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002557 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002558 case Decl::LinkageSpec:
2559 case Decl::ObjCPropertyImpl:
2560 case Decl::FileScopeAsm:
2561 case Decl::StaticAssert:
2562 case Decl::Block:
2563 return C;
2564
2565 // Declaration kinds that don't make any sense here, but are
2566 // nonetheless harmless.
2567 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002568 break;
2569
2570 // Declaration kinds for which the definition is not resolvable.
2571 case Decl::UnresolvedUsingTypename:
2572 case Decl::UnresolvedUsingValue:
2573 break;
2574
2575 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002576 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2577 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002578
2579 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002580 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002581
2582 case Decl::Enum:
2583 case Decl::Record:
2584 case Decl::CXXRecord:
2585 case Decl::ClassTemplateSpecialization:
2586 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002587 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002588 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002589 return clang_getNullCursor();
2590
2591 case Decl::Function:
2592 case Decl::CXXMethod:
2593 case Decl::CXXConstructor:
2594 case Decl::CXXDestructor:
2595 case Decl::CXXConversion: {
2596 const FunctionDecl *Def = 0;
2597 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002598 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002599 return clang_getNullCursor();
2600 }
2601
2602 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002603 // Ask the variable if it has a definition.
2604 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2605 return MakeCXCursor(Def, CXXUnit);
2606 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002607 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002608
Douglas Gregorb6998662010-01-19 19:34:47 +00002609 case Decl::FunctionTemplate: {
2610 const FunctionDecl *Def = 0;
2611 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002612 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002613 return clang_getNullCursor();
2614 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002615
Douglas Gregorb6998662010-01-19 19:34:47 +00002616 case Decl::ClassTemplate: {
2617 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002618 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002619 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002620 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002621 return clang_getNullCursor();
2622 }
2623
2624 case Decl::Using: {
2625 UsingDecl *Using = cast<UsingDecl>(D);
2626 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002627 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2628 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002629 S != SEnd; ++S) {
2630 if (Def != clang_getNullCursor()) {
2631 // FIXME: We have no way to return multiple results.
2632 return clang_getNullCursor();
2633 }
2634
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002635 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002636 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002637 }
2638
2639 return Def;
2640 }
2641
2642 case Decl::UsingShadow:
2643 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002644 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002645 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002646
2647 case Decl::ObjCMethod: {
2648 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2649 if (Method->isThisDeclarationADefinition())
2650 return C;
2651
2652 // Dig out the method definition in the associated
2653 // @implementation, if we have it.
2654 // FIXME: The ASTs should make finding the definition easier.
2655 if (ObjCInterfaceDecl *Class
2656 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2657 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2658 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2659 Method->isInstanceMethod()))
2660 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002661 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002662
2663 return clang_getNullCursor();
2664 }
2665
2666 case Decl::ObjCCategory:
2667 if (ObjCCategoryImplDecl *Impl
2668 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002669 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002670 return clang_getNullCursor();
2671
2672 case Decl::ObjCProtocol:
2673 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2674 return C;
2675 return clang_getNullCursor();
2676
2677 case Decl::ObjCInterface:
2678 // There are two notions of a "definition" for an Objective-C
2679 // class: the interface and its implementation. When we resolved a
2680 // reference to an Objective-C class, produce the @interface as
2681 // the definition; when we were provided with the interface,
2682 // produce the @implementation as the definition.
2683 if (WasReference) {
2684 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2685 return C;
2686 } else if (ObjCImplementationDecl *Impl
2687 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002688 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002689 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002690
Douglas Gregorb6998662010-01-19 19:34:47 +00002691 case Decl::ObjCProperty:
2692 // FIXME: We don't really know where to find the
2693 // ObjCPropertyImplDecls that implement this property.
2694 return clang_getNullCursor();
2695
2696 case Decl::ObjCCompatibleAlias:
2697 if (ObjCInterfaceDecl *Class
2698 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2699 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002700 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002701
Douglas Gregorb6998662010-01-19 19:34:47 +00002702 return clang_getNullCursor();
2703
2704 case Decl::ObjCForwardProtocol: {
2705 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2706 if (Forward->protocol_size() == 1)
2707 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002708 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002709 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002710
2711 // FIXME: Cannot return multiple definitions.
2712 return clang_getNullCursor();
2713 }
2714
2715 case Decl::ObjCClass: {
2716 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2717 if (Class->size() == 1) {
2718 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2719 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002720 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002721 return clang_getNullCursor();
2722 }
2723
2724 // FIXME: Cannot return multiple definitions.
2725 return clang_getNullCursor();
2726 }
2727
2728 case Decl::Friend:
2729 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002730 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002731 return clang_getNullCursor();
2732
2733 case Decl::FriendTemplate:
2734 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002735 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002736 return clang_getNullCursor();
2737 }
2738
2739 return clang_getNullCursor();
2740}
2741
2742unsigned clang_isCursorDefinition(CXCursor C) {
2743 if (!clang_isDeclaration(C.kind))
2744 return 0;
2745
2746 return clang_getCursorDefinition(C) == C;
2747}
2748
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002749void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002750 const char **startBuf,
2751 const char **endBuf,
2752 unsigned *startLine,
2753 unsigned *startColumn,
2754 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002755 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002756 assert(getCursorDecl(C) && "CXCursor has null decl");
2757 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002758 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2759 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002760
Steve Naroff4ade6d62009-09-23 17:52:52 +00002761 SourceManager &SM = FD->getASTContext().getSourceManager();
2762 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2763 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2764 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2765 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2766 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2767 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2768}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002769
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002770void clang_enableStackTraces(void) {
2771 llvm::sys::PrintStackTraceOnErrorSignal();
2772}
2773
Ted Kremenekfb480492010-01-13 21:46:36 +00002774} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002775
Ted Kremenekfb480492010-01-13 21:46:36 +00002776//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002777// Token-based Operations.
2778//===----------------------------------------------------------------------===//
2779
2780/* CXToken layout:
2781 * int_data[0]: a CXTokenKind
2782 * int_data[1]: starting token location
2783 * int_data[2]: token length
2784 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002785 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002786 * otherwise unused.
2787 */
2788extern "C" {
2789
2790CXTokenKind clang_getTokenKind(CXToken CXTok) {
2791 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2792}
2793
2794CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2795 switch (clang_getTokenKind(CXTok)) {
2796 case CXToken_Identifier:
2797 case CXToken_Keyword:
2798 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002799 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2800 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002801
2802 case CXToken_Literal: {
2803 // We have stashed the starting pointer in the ptr_data field. Use it.
2804 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002805 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002806 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002807
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002808 case CXToken_Punctuation:
2809 case CXToken_Comment:
2810 break;
2811 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002812
2813 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002814 // deconstructing the source location.
2815 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2816 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002817 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002818
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002819 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2820 std::pair<FileID, unsigned> LocInfo
2821 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002822 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002823 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002824 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2825 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002826 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002827
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002828 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002829}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002830
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002831CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2832 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2833 if (!CXXUnit)
2834 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002835
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002836 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2837 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2838}
2839
2840CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2841 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002842 if (!CXXUnit)
2843 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002844
2845 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002846 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2847}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002848
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002849void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2850 CXToken **Tokens, unsigned *NumTokens) {
2851 if (Tokens)
2852 *Tokens = 0;
2853 if (NumTokens)
2854 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002855
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002856 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2857 if (!CXXUnit || !Tokens || !NumTokens)
2858 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002859
Douglas Gregorbdf60622010-03-05 21:16:25 +00002860 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2861
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002862 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002863 if (R.isInvalid())
2864 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002865
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002866 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2867 std::pair<FileID, unsigned> BeginLocInfo
2868 = SourceMgr.getDecomposedLoc(R.getBegin());
2869 std::pair<FileID, unsigned> EndLocInfo
2870 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002871
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002872 // Cannot tokenize across files.
2873 if (BeginLocInfo.first != EndLocInfo.first)
2874 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002875
2876 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002877 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002878 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002879 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002880 if (Invalid)
2881 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002882
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002883 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2884 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002885 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002886 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002887
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002888 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002889 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002890 llvm::SmallVector<CXToken, 32> CXTokens;
2891 Token Tok;
2892 do {
2893 // Lex the next token
2894 Lex.LexFromRawLexer(Tok);
2895 if (Tok.is(tok::eof))
2896 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002897
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002898 // Initialize the CXToken.
2899 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002900
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002901 // - Common fields
2902 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2903 CXTok.int_data[2] = Tok.getLength();
2904 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002905
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002906 // - Kind-specific fields
2907 if (Tok.isLiteral()) {
2908 CXTok.int_data[0] = CXToken_Literal;
2909 CXTok.ptr_data = (void *)Tok.getLiteralData();
2910 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002911 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002912 std::pair<FileID, unsigned> LocInfo
2913 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002914 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002915 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002916 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2917 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002918 return;
2919
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002920 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002921 IdentifierInfo *II
2922 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002923
2924 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2925 CXTok.int_data[0] = CXToken_Keyword;
2926 }
2927 else {
2928 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2929 CXToken_Identifier
2930 : CXToken_Keyword;
2931 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002932 CXTok.ptr_data = II;
2933 } else if (Tok.is(tok::comment)) {
2934 CXTok.int_data[0] = CXToken_Comment;
2935 CXTok.ptr_data = 0;
2936 } else {
2937 CXTok.int_data[0] = CXToken_Punctuation;
2938 CXTok.ptr_data = 0;
2939 }
2940 CXTokens.push_back(CXTok);
2941 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002942
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002943 if (CXTokens.empty())
2944 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002945
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002946 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2947 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2948 *NumTokens = CXTokens.size();
2949}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002950
Ted Kremenek6db61092010-05-05 00:55:15 +00002951void clang_disposeTokens(CXTranslationUnit TU,
2952 CXToken *Tokens, unsigned NumTokens) {
2953 free(Tokens);
2954}
2955
2956} // end: extern "C"
2957
2958//===----------------------------------------------------------------------===//
2959// Token annotation APIs.
2960//===----------------------------------------------------------------------===//
2961
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002962typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002963static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2964 CXCursor parent,
2965 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002966namespace {
2967class AnnotateTokensWorker {
2968 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002969 CXToken *Tokens;
2970 CXCursor *Cursors;
2971 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002972 unsigned TokIdx;
2973 CursorVisitor AnnotateVis;
2974 SourceManager &SrcMgr;
2975
2976 bool MoreTokens() const { return TokIdx < NumTokens; }
2977 unsigned NextToken() const { return TokIdx; }
2978 void AdvanceToken() { ++TokIdx; }
2979 SourceLocation GetTokenLoc(unsigned tokI) {
2980 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2981 }
2982
Ted Kremenek6db61092010-05-05 00:55:15 +00002983public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002984 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002985 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2986 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002987 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002988 NumTokens(numTokens), TokIdx(0),
2989 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2990 Decl::MaxPCHLevel, RegionOfInterest),
2991 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002992
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002993 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002994 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002995 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002996};
2997}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002998
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002999void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3000 // Walk the AST within the region of interest, annotating tokens
3001 // along the way.
3002 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003003
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003004 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3005 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3006 if (Pos != Annotated.end())
3007 Cursors[I] = Pos->second;
3008 }
3009
3010 // Finish up annotating any tokens left.
3011 if (!MoreTokens())
3012 return;
3013
3014 const CXCursor &C = clang_getNullCursor();
3015 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3016 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3017 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003018 }
3019}
3020
Ted Kremenek6db61092010-05-05 00:55:15 +00003021enum CXChildVisitResult
3022AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003023 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3024 // We can always annotate a preprocessing directive/macro instantiation.
3025 if (clang_isPreprocessing(cursor.kind)) {
3026 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003027 return CXChildVisit_Recurse;
3028 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003029
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003030 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003031
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003032 if (cursorRange.isInvalid())
3033 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003034
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003035 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3036
Ted Kremeneka333c662010-05-12 05:29:33 +00003037 // Adjust the annotated range based specific declarations.
3038 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3039 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003040 Decl *D = cxcursor::getCursorDecl(cursor);
3041 // Don't visit synthesized ObjC methods, since they have no syntatic
3042 // representation in the source.
3043 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3044 if (MD->isSynthesized())
3045 return CXChildVisit_Continue;
3046 }
3047 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003048 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3049 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003050 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003051 if (TLoc.isValid() &&
3052 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003053 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003054 }
3055 }
3056 }
3057
Ted Kremenek3f404602010-08-14 01:14:06 +00003058 // If the location of the cursor occurs within a macro instantiation, record
3059 // the spelling location of the cursor in our annotation map. We can then
3060 // paper over the token labelings during a post-processing step to try and
3061 // get cursor mappings for tokens that are the *arguments* of a macro
3062 // instantiation.
3063 if (L.isMacroID()) {
3064 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3065 // Only invalidate the old annotation if it isn't part of a preprocessing
3066 // directive. Here we assume that the default construction of CXCursor
3067 // results in CXCursor.kind being an initialized value (i.e., 0). If
3068 // this isn't the case, we can fix by doing lookup + insertion.
3069
3070 CXCursor &oldC = Annotated[rawEncoding];
3071 if (!clang_isPreprocessing(oldC.kind))
3072 oldC = cursor;
3073 }
3074
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003075 const enum CXCursorKind K = clang_getCursorKind(parent);
3076 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003077 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3078 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003079
3080 while (MoreTokens()) {
3081 const unsigned I = NextToken();
3082 SourceLocation TokLoc = GetTokenLoc(I);
3083 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3084 case RangeBefore:
3085 Cursors[I] = updateC;
3086 AdvanceToken();
3087 continue;
3088 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003089 case RangeOverlap:
3090 break;
3091 }
3092 break;
3093 }
3094
3095 // Visit children to get their cursor information.
3096 const unsigned BeforeChildren = NextToken();
3097 VisitChildren(cursor);
3098 const unsigned AfterChildren = NextToken();
3099
3100 // Adjust 'Last' to the last token within the extent of the cursor.
3101 while (MoreTokens()) {
3102 const unsigned I = NextToken();
3103 SourceLocation TokLoc = GetTokenLoc(I);
3104 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3105 case RangeBefore:
3106 assert(0 && "Infeasible");
3107 case RangeAfter:
3108 break;
3109 case RangeOverlap:
3110 Cursors[I] = updateC;
3111 AdvanceToken();
3112 continue;
3113 }
3114 break;
3115 }
3116 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003117
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003118 // Scan the tokens that are at the beginning of the cursor, but are not
3119 // capture by the child cursors.
3120
3121 // For AST elements within macros, rely on a post-annotate pass to
3122 // to correctly annotate the tokens with cursors. Otherwise we can
3123 // get confusing results of having tokens that map to cursors that really
3124 // are expanded by an instantiation.
3125 if (L.isMacroID())
3126 cursor = clang_getNullCursor();
3127
3128 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3129 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3130 break;
3131 Cursors[I] = cursor;
3132 }
3133 // Scan the tokens that are at the end of the cursor, but are not captured
3134 // but the child cursors.
3135 for (unsigned I = AfterChildren; I != Last; ++I)
3136 Cursors[I] = cursor;
3137
3138 TokIdx = Last;
3139 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003140}
3141
Ted Kremenek6db61092010-05-05 00:55:15 +00003142static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3143 CXCursor parent,
3144 CXClientData client_data) {
3145 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3146}
3147
3148extern "C" {
3149
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003150void clang_annotateTokens(CXTranslationUnit TU,
3151 CXToken *Tokens, unsigned NumTokens,
3152 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003153
3154 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003155 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003156
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003157 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003158 if (!CXXUnit) {
3159 // Any token we don't specifically annotate will have a NULL cursor.
3160 const CXCursor &C = clang_getNullCursor();
3161 for (unsigned I = 0; I != NumTokens; ++I)
3162 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003163 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003164 }
3165
Douglas Gregorbdf60622010-03-05 21:16:25 +00003166 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003167
Douglas Gregor0396f462010-03-19 05:22:59 +00003168 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003169 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003170 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3171 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003172 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3173 clang_getTokenLocation(TU,
3174 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003175
Douglas Gregor0396f462010-03-19 05:22:59 +00003176 // A mapping from the source locations found when re-lexing or traversing the
3177 // region of interest to the corresponding cursors.
3178 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003179
3180 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003181 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003182 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3183 std::pair<FileID, unsigned> BeginLocInfo
3184 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3185 std::pair<FileID, unsigned> EndLocInfo
3186 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003187
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003188 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003189 bool Invalid = false;
3190 if (BeginLocInfo.first == EndLocInfo.first &&
3191 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3192 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003193 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3194 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003195 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003196 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003197 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003198
3199 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003200 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003201 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003202 Token Tok;
3203 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003204
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003205 reprocess:
3206 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3207 // We have found a preprocessing directive. Gobble it up so that we
3208 // don't see it while preprocessing these tokens later, but keep track of
3209 // all of the token locations inside this preprocessing directive so that
3210 // we can annotate them appropriately.
3211 //
3212 // FIXME: Some simple tests here could identify macro definitions and
3213 // #undefs, to provide specific cursor kinds for those.
3214 std::vector<SourceLocation> Locations;
3215 do {
3216 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003217 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003218 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003219
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003220 using namespace cxcursor;
3221 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003222 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3223 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003224 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003225 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3226 Annotated[Locations[I].getRawEncoding()] = Cursor;
3227 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003228
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003229 if (Tok.isAtStartOfLine())
3230 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003231
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003232 continue;
3233 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003234
Douglas Gregor48072312010-03-18 15:23:44 +00003235 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003236 break;
3237 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003238 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003239
Douglas Gregor0396f462010-03-19 05:22:59 +00003240 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003241 // a specific cursor.
3242 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3243 CXXUnit, RegionOfInterest);
3244 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003245}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003246} // end: extern "C"
3247
3248//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003249// Operations for querying linkage of a cursor.
3250//===----------------------------------------------------------------------===//
3251
3252extern "C" {
3253CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003254 if (!clang_isDeclaration(cursor.kind))
3255 return CXLinkage_Invalid;
3256
Ted Kremenek16b42592010-03-03 06:36:57 +00003257 Decl *D = cxcursor::getCursorDecl(cursor);
3258 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3259 switch (ND->getLinkage()) {
3260 case NoLinkage: return CXLinkage_NoLinkage;
3261 case InternalLinkage: return CXLinkage_Internal;
3262 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3263 case ExternalLinkage: return CXLinkage_External;
3264 };
3265
3266 return CXLinkage_Invalid;
3267}
3268} // end: extern "C"
3269
3270//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003271// Operations for querying language of a cursor.
3272//===----------------------------------------------------------------------===//
3273
3274static CXLanguageKind getDeclLanguage(const Decl *D) {
3275 switch (D->getKind()) {
3276 default:
3277 break;
3278 case Decl::ImplicitParam:
3279 case Decl::ObjCAtDefsField:
3280 case Decl::ObjCCategory:
3281 case Decl::ObjCCategoryImpl:
3282 case Decl::ObjCClass:
3283 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003284 case Decl::ObjCForwardProtocol:
3285 case Decl::ObjCImplementation:
3286 case Decl::ObjCInterface:
3287 case Decl::ObjCIvar:
3288 case Decl::ObjCMethod:
3289 case Decl::ObjCProperty:
3290 case Decl::ObjCPropertyImpl:
3291 case Decl::ObjCProtocol:
3292 return CXLanguage_ObjC;
3293 case Decl::CXXConstructor:
3294 case Decl::CXXConversion:
3295 case Decl::CXXDestructor:
3296 case Decl::CXXMethod:
3297 case Decl::CXXRecord:
3298 case Decl::ClassTemplate:
3299 case Decl::ClassTemplatePartialSpecialization:
3300 case Decl::ClassTemplateSpecialization:
3301 case Decl::Friend:
3302 case Decl::FriendTemplate:
3303 case Decl::FunctionTemplate:
3304 case Decl::LinkageSpec:
3305 case Decl::Namespace:
3306 case Decl::NamespaceAlias:
3307 case Decl::NonTypeTemplateParm:
3308 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003309 case Decl::TemplateTemplateParm:
3310 case Decl::TemplateTypeParm:
3311 case Decl::UnresolvedUsingTypename:
3312 case Decl::UnresolvedUsingValue:
3313 case Decl::Using:
3314 case Decl::UsingDirective:
3315 case Decl::UsingShadow:
3316 return CXLanguage_CPlusPlus;
3317 }
3318
3319 return CXLanguage_C;
3320}
3321
3322extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003323
3324enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3325 if (clang_isDeclaration(cursor.kind))
3326 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3327 if (D->hasAttr<UnavailableAttr>() ||
3328 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3329 return CXAvailability_Available;
3330
3331 if (D->hasAttr<DeprecatedAttr>())
3332 return CXAvailability_Deprecated;
3333 }
3334
3335 return CXAvailability_Available;
3336}
3337
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003338CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3339 if (clang_isDeclaration(cursor.kind))
3340 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3341
3342 return CXLanguage_Invalid;
3343}
3344} // end: extern "C"
3345
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003346
3347//===----------------------------------------------------------------------===//
3348// C++ AST instrospection.
3349//===----------------------------------------------------------------------===//
3350
3351extern "C" {
3352unsigned clang_CXXMethod_isStatic(CXCursor C) {
3353 if (!clang_isDeclaration(C.kind))
3354 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003355
3356 CXXMethodDecl *Method = 0;
3357 Decl *D = cxcursor::getCursorDecl(C);
3358 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3359 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3360 else
3361 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3362 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003363}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003364
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003365} // end: extern "C"
3366
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003367//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003368// Attribute introspection.
3369//===----------------------------------------------------------------------===//
3370
3371extern "C" {
3372CXType clang_getIBOutletCollectionType(CXCursor C) {
3373 if (C.kind != CXCursor_IBOutletCollectionAttr)
3374 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3375
3376 IBOutletCollectionAttr *A =
3377 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3378
3379 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3380}
3381} // end: extern "C"
3382
3383//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003384// CXString Operations.
3385//===----------------------------------------------------------------------===//
3386
3387extern "C" {
3388const char *clang_getCString(CXString string) {
3389 return string.Spelling;
3390}
3391
3392void clang_disposeString(CXString string) {
3393 if (string.MustFreeString && string.Spelling)
3394 free((void*)string.Spelling);
3395}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003396
Ted Kremenekfb480492010-01-13 21:46:36 +00003397} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003398
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003399namespace clang { namespace cxstring {
3400CXString createCXString(const char *String, bool DupString){
3401 CXString Str;
3402 if (DupString) {
3403 Str.Spelling = strdup(String);
3404 Str.MustFreeString = 1;
3405 } else {
3406 Str.Spelling = String;
3407 Str.MustFreeString = 0;
3408 }
3409 return Str;
3410}
3411
3412CXString createCXString(llvm::StringRef String, bool DupString) {
3413 CXString Result;
3414 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3415 char *Spelling = (char *)malloc(String.size() + 1);
3416 memmove(Spelling, String.data(), String.size());
3417 Spelling[String.size()] = 0;
3418 Result.Spelling = Spelling;
3419 Result.MustFreeString = 1;
3420 } else {
3421 Result.Spelling = String.data();
3422 Result.MustFreeString = 0;
3423 }
3424 return Result;
3425}
3426}}
3427
Ted Kremenek04bb7162010-01-22 22:44:15 +00003428//===----------------------------------------------------------------------===//
3429// Misc. utility functions.
3430//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003431
Ted Kremenek04bb7162010-01-22 22:44:15 +00003432extern "C" {
3433
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003434CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003435 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003436}
3437
3438} // end: extern "C"