blob: d849186324426df7ada4b3dd0b8e1f2d9fe24c99 [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 Gregor0a35bce2010-09-01 03:07:18 +0000320 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
321
Douglas Gregor01829d32010-08-31 14:41:23 +0000322 // Name visitor
323 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
324
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000325 // Template visitors
326 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000327 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000328 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
329
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000330 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000331 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000332 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000333 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000334 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
335 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000336 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000337 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000338 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000339 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
340 bool VisitPointerTypeLoc(PointerTypeLoc TL);
341 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
342 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
343 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
344 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000345 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000346 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000347 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000348 // FIXME: Implement visitors here when the unimplemented TypeLocs get
349 // implemented
350 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
351 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000352
Douglas Gregora59e3902010-01-21 23:27:09 +0000353 // Statement visitors
354 bool VisitStmt(Stmt *S);
355 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000356 // FIXME: LabelStmt label?
357 bool VisitIfStmt(IfStmt *S);
358 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000359 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000360 bool VisitWhileStmt(WhileStmt *S);
361 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000362// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000363
Douglas Gregor336fd812010-01-23 00:40:08 +0000364 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000365 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
366 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000367 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000368 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000369 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000370 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000371 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000372 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000373 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000374 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000375 // FIXME: AddrLabelExpr (once we have cursors for labels)
376 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
377 bool VisitVAArgExpr(VAArgExpr *E);
378 // FIXME: InitListExpr (for the designators)
379 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000380};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000381
Ted Kremenekab188932010-01-05 19:32:54 +0000382} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000383
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000384static SourceRange getRawCursorExtent(CXCursor C);
385
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000386RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000387 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
388}
389
Douglas Gregorb1373d02010-01-20 20:59:29 +0000390/// \brief Visit the given cursor and, if requested by the visitor,
391/// its children.
392///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000393/// \param Cursor the cursor to visit.
394///
395/// \param CheckRegionOfInterest if true, then the caller already checked that
396/// this cursor is within the region of interest.
397///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000398/// \returns true if the visitation should be aborted, false if it
399/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000400bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000401 if (clang_isInvalid(Cursor.kind))
402 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000403
Douglas Gregorb1373d02010-01-20 20:59:29 +0000404 if (clang_isDeclaration(Cursor.kind)) {
405 Decl *D = getCursorDecl(Cursor);
406 assert(D && "Invalid declaration cursor");
407 if (D->getPCHLevel() > MaxPCHLevel)
408 return false;
409
410 if (D->isImplicit())
411 return false;
412 }
413
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000414 // If we have a range of interest, and this cursor doesn't intersect with it,
415 // we're done.
416 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000417 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000418 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000419 return false;
420 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000421
Douglas Gregorb1373d02010-01-20 20:59:29 +0000422 switch (Visitor(Cursor, Parent, ClientData)) {
423 case CXChildVisit_Break:
424 return true;
425
426 case CXChildVisit_Continue:
427 return false;
428
429 case CXChildVisit_Recurse:
430 return VisitChildren(Cursor);
431 }
432
Douglas Gregorfd643772010-01-25 16:45:46 +0000433 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434}
435
Douglas Gregor788f5a12010-03-20 00:41:21 +0000436std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
437CursorVisitor::getPreprocessedEntities() {
438 PreprocessingRecord &PPRec
439 = *TU->getPreprocessor().getPreprocessingRecord();
440
441 bool OnlyLocalDecls
442 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
443
444 // There is no region of interest; we have to walk everything.
445 if (RegionOfInterest.isInvalid())
446 return std::make_pair(PPRec.begin(OnlyLocalDecls),
447 PPRec.end(OnlyLocalDecls));
448
449 // Find the file in which the region of interest lands.
450 SourceManager &SM = TU->getSourceManager();
451 std::pair<FileID, unsigned> Begin
452 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
453 std::pair<FileID, unsigned> End
454 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
455
456 // The region of interest spans files; we have to walk everything.
457 if (Begin.first != End.first)
458 return std::make_pair(PPRec.begin(OnlyLocalDecls),
459 PPRec.end(OnlyLocalDecls));
460
461 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
462 = TU->getPreprocessedEntitiesByFile();
463 if (ByFileMap.empty()) {
464 // Build the mapping from files to sets of preprocessed entities.
465 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
466 EEnd = PPRec.end(OnlyLocalDecls);
467 E != EEnd; ++E) {
468 std::pair<FileID, unsigned> P
469 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
470 ByFileMap[P.first].push_back(*E);
471 }
472 }
473
474 return std::make_pair(ByFileMap[Begin.first].begin(),
475 ByFileMap[Begin.first].end());
476}
477
Douglas Gregorb1373d02010-01-20 20:59:29 +0000478/// \brief Visit the children of the given cursor.
479///
480/// \returns true if the visitation should be aborted, false if it
481/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000482bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000483 if (clang_isReference(Cursor.kind)) {
484 // By definition, references have no children.
485 return false;
486 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000487
488 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000489 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000490 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000491
Douglas Gregorb1373d02010-01-20 20:59:29 +0000492 if (clang_isDeclaration(Cursor.kind)) {
493 Decl *D = getCursorDecl(Cursor);
494 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000495 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000496 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000497
Douglas Gregora59e3902010-01-21 23:27:09 +0000498 if (clang_isStatement(Cursor.kind))
499 return Visit(getCursorStmt(Cursor));
500 if (clang_isExpression(Cursor.kind))
501 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000502
Douglas Gregorb1373d02010-01-20 20:59:29 +0000503 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000504 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000505 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
506 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000507 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
508 TLEnd = CXXUnit->top_level_end();
509 TL != TLEnd; ++TL) {
510 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000511 return true;
512 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000513 } else if (VisitDeclContext(
514 CXXUnit->getASTContext().getTranslationUnitDecl()))
515 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000516
Douglas Gregor0396f462010-03-19 05:22:59 +0000517 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000518 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000519 // FIXME: Once we have the ability to deserialize a preprocessing record,
520 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000521 PreprocessingRecord::iterator E, EEnd;
522 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000523 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
524 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
525 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000526
Douglas Gregor0396f462010-03-19 05:22:59 +0000527 continue;
528 }
529
530 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
531 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
532 return true;
533
534 continue;
535 }
536 }
537 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000538 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000539 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000540
Douglas Gregorb1373d02010-01-20 20:59:29 +0000541 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000542 return false;
543}
544
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000545bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000546 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
547 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000548
Ted Kremenek664cffd2010-07-22 11:30:19 +0000549 if (Stmt *Body = B->getBody())
550 return Visit(MakeCXCursor(Body, StmtParent, TU));
551
552 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000553}
554
Douglas Gregorb1373d02010-01-20 20:59:29 +0000555bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000556 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000557 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000558
Ted Kremenek23173d72010-05-18 21:09:07 +0000559 Decl *D = *I;
560 if (D->getLexicalDeclContext() != DC)
561 continue;
562
563 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000564
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000565 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000566 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000567 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000568 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000569
570 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000571 case RangeBefore:
572 // This declaration comes before the region of interest; skip it.
573 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000574
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000575 case RangeAfter:
576 // This declaration comes after the region of interest; we're done.
577 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000578
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000579 case RangeOverlap:
580 // This declaration overlaps the region of interest; visit it.
581 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000582 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000583 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000584
Daniel Dunbard52864b2010-02-14 10:02:57 +0000585 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000586 return true;
587 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000588
Douglas Gregorb1373d02010-01-20 20:59:29 +0000589 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000590}
591
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000592bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
593 llvm_unreachable("Translation units are visited directly by Visit()");
594 return false;
595}
596
597bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
598 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
599 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000600
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000601 return false;
602}
603
604bool CursorVisitor::VisitTagDecl(TagDecl *D) {
605 return VisitDeclContext(D);
606}
607
Douglas Gregor74dbe642010-08-31 19:31:58 +0000608bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
609 ClassTemplatePartialSpecializationDecl *D) {
610 // FIXME: Visit the "outer" template parameter lists on the TagDecl
611 // before visiting these template parameters.
612 if (VisitTemplateParameters(D->getTemplateParameters()))
613 return true;
614
615 // Visit the partial specialization arguments.
616 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
617 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
618 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
619 return true;
620
621 return VisitCXXRecordDecl(D);
622}
623
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000624bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
625 // FIXME: Visit default argument
626 return false;
627}
628
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000629bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
630 if (Expr *Init = D->getInitExpr())
631 return Visit(MakeCXCursor(Init, StmtParent, TU));
632 return false;
633}
634
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000635bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
636 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
637 if (Visit(TSInfo->getTypeLoc()))
638 return true;
639
640 return false;
641}
642
Douglas Gregorb1373d02010-01-20 20:59:29 +0000643bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000644 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
645 // Visit the function declaration's syntactic components in the order
646 // written. This requires a bit of work.
647 TypeLoc TL = TSInfo->getTypeLoc();
648 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
649
650 // If we have a function declared directly (without the use of a typedef),
651 // visit just the return type. Otherwise, just visit the function's type
652 // now.
653 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
654 (!FTL && Visit(TL)))
655 return true;
656
657 // FIXME: Visit the nested-name-specifier, if present.
658
659 // Visit the declaration name.
660 if (VisitDeclarationNameInfo(ND->getNameInfo()))
661 return true;
662
663 // FIXME: Visit explicitly-specified template arguments!
664
665 // Visit the function parameters, if we have a function type.
666 if (FTL && VisitFunctionTypeLoc(*FTL, true))
667 return true;
668
669 // FIXME: Attributes?
670 }
671
Douglas Gregora59e3902010-01-21 23:27:09 +0000672 if (ND->isThisDeclarationADefinition() &&
673 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
674 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000675
Douglas Gregorb1373d02010-01-20 20:59:29 +0000676 return false;
677}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000678
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000679bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
680 if (VisitDeclaratorDecl(D))
681 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000682
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000683 if (Expr *BitWidth = D->getBitWidth())
684 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000685
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000686 return false;
687}
688
689bool CursorVisitor::VisitVarDecl(VarDecl *D) {
690 if (VisitDeclaratorDecl(D))
691 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000692
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000693 if (Expr *Init = D->getInit())
694 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000695
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000696 return false;
697}
698
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000699bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
700 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
701 // before visiting these template parameters.
702 if (VisitTemplateParameters(D->getTemplateParameters()))
703 return true;
704
705 return VisitFunctionDecl(D->getTemplatedDecl());
706}
707
Douglas Gregor39d6f072010-08-31 19:02:00 +0000708bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
709 // FIXME: Visit the "outer" template parameter lists on the TagDecl
710 // before visiting these template parameters.
711 if (VisitTemplateParameters(D->getTemplateParameters()))
712 return true;
713
714 return VisitCXXRecordDecl(D->getTemplatedDecl());
715}
716
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000717bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000718 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
719 if (Visit(TSInfo->getTypeLoc()))
720 return true;
721
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000722 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000723 PEnd = ND->param_end();
724 P != PEnd; ++P) {
725 if (Visit(MakeCXCursor(*P, TU)))
726 return true;
727 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000728
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000729 if (ND->isThisDeclarationADefinition() &&
730 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
731 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000732
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000733 return false;
734}
735
Douglas Gregora59e3902010-01-21 23:27:09 +0000736bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
737 return VisitDeclContext(D);
738}
739
Douglas Gregorb1373d02010-01-20 20:59:29 +0000740bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000741 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
742 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000743 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000744
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000745 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
746 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
747 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000748 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000749 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000750
Douglas Gregora59e3902010-01-21 23:27:09 +0000751 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000752}
753
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000754bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
755 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
756 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
757 E = PID->protocol_end(); I != E; ++I, ++PL)
758 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
759 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000760
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000761 return VisitObjCContainerDecl(PID);
762}
763
Ted Kremenek23173d72010-05-18 21:09:07 +0000764bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000765 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
766 return true;
767
Ted Kremenek23173d72010-05-18 21:09:07 +0000768 // FIXME: This implements a workaround with @property declarations also being
769 // installed in the DeclContext for the @interface. Eventually this code
770 // should be removed.
771 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
772 if (!CDecl || !CDecl->IsClassExtension())
773 return false;
774
775 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
776 if (!ID)
777 return false;
778
779 IdentifierInfo *PropertyId = PD->getIdentifier();
780 ObjCPropertyDecl *prevDecl =
781 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
782
783 if (!prevDecl)
784 return false;
785
786 // Visit synthesized methods since they will be skipped when visiting
787 // the @interface.
788 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
789 if (MD->isSynthesized())
790 if (Visit(MakeCXCursor(MD, TU)))
791 return true;
792
793 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
794 if (MD->isSynthesized())
795 if (Visit(MakeCXCursor(MD, TU)))
796 return true;
797
798 return false;
799}
800
Douglas Gregorb1373d02010-01-20 20:59:29 +0000801bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000802 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000803 if (D->getSuperClass() &&
804 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000805 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000806 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000807 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000808
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000809 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
810 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
811 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000812 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000813 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000814
Douglas Gregora59e3902010-01-21 23:27:09 +0000815 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000816}
817
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000818bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
819 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000820}
821
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000822bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000823 // 'ID' could be null when dealing with invalid code.
824 if (ObjCInterfaceDecl *ID = D->getClassInterface())
825 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
826 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000827
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000828 return VisitObjCImplDecl(D);
829}
830
831bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
832#if 0
833 // Issue callbacks for super class.
834 // FIXME: No source location information!
835 if (D->getSuperClass() &&
836 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000837 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000838 TU)))
839 return true;
840#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000841
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000842 return VisitObjCImplDecl(D);
843}
844
845bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
846 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
847 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
848 E = D->protocol_end();
849 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000850 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000851 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000852
853 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000854}
855
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000856bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
857 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
858 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
859 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000860
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000861 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000862}
863
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000864bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
865 return VisitDeclContext(D);
866}
867
Douglas Gregor69319002010-08-31 23:48:11 +0000868bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
869 // FIXME: Visit nested-name-specifier
870
871 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
872 D->getTargetNameLoc(), TU));
873}
874
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000875bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
876 // FIXME: Visit nested-name-specifier
877
878 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
879 D->getIdentLocation(), TU));
880}
881
Douglas Gregor01829d32010-08-31 14:41:23 +0000882bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
883 switch (Name.getName().getNameKind()) {
884 case clang::DeclarationName::Identifier:
885 case clang::DeclarationName::CXXLiteralOperatorName:
886 case clang::DeclarationName::CXXOperatorName:
887 case clang::DeclarationName::CXXUsingDirective:
888 return false;
889
890 case clang::DeclarationName::CXXConstructorName:
891 case clang::DeclarationName::CXXDestructorName:
892 case clang::DeclarationName::CXXConversionFunctionName:
893 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
894 return Visit(TSInfo->getTypeLoc());
895 return false;
896
897 case clang::DeclarationName::ObjCZeroArgSelector:
898 case clang::DeclarationName::ObjCOneArgSelector:
899 case clang::DeclarationName::ObjCMultiArgSelector:
900 // FIXME: Per-identifier location info?
901 return false;
902 }
903
904 return false;
905}
906
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000907bool CursorVisitor::VisitTemplateParameters(
908 const TemplateParameterList *Params) {
909 if (!Params)
910 return false;
911
912 for (TemplateParameterList::const_iterator P = Params->begin(),
913 PEnd = Params->end();
914 P != PEnd; ++P) {
915 if (Visit(MakeCXCursor(*P, TU)))
916 return true;
917 }
918
919 return false;
920}
921
Douglas Gregor0b36e612010-08-31 20:37:03 +0000922bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
923 switch (Name.getKind()) {
924 case TemplateName::Template:
925 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
926
927 case TemplateName::OverloadedTemplate:
928 // FIXME: We need a way to return multiple lookup results in a single
929 // cursor.
930 return false;
931
932 case TemplateName::DependentTemplate:
933 // FIXME: Visit nested-name-specifier.
934 return false;
935
936 case TemplateName::QualifiedTemplate:
937 // FIXME: Visit nested-name-specifier.
938 return Visit(MakeCursorTemplateRef(
939 Name.getAsQualifiedTemplateName()->getDecl(),
940 Loc, TU));
941 }
942
943 return false;
944}
945
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000946bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
947 switch (TAL.getArgument().getKind()) {
948 case TemplateArgument::Null:
949 case TemplateArgument::Integral:
950 return false;
951
952 case TemplateArgument::Pack:
953 // FIXME: Implement when variadic templates come along.
954 return false;
955
956 case TemplateArgument::Type:
957 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
958 return Visit(TSInfo->getTypeLoc());
959 return false;
960
961 case TemplateArgument::Declaration:
962 if (Expr *E = TAL.getSourceDeclExpression())
963 return Visit(MakeCXCursor(E, StmtParent, TU));
964 return false;
965
966 case TemplateArgument::Expression:
967 if (Expr *E = TAL.getSourceExpression())
968 return Visit(MakeCXCursor(E, StmtParent, TU));
969 return false;
970
971 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +0000972 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
973 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000974 }
975
976 return false;
977}
978
Ted Kremeneka0536d82010-05-07 01:04:29 +0000979bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
980 return VisitDeclContext(D);
981}
982
Douglas Gregor01829d32010-08-31 14:41:23 +0000983bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
984 return Visit(TL.getUnqualifiedLoc());
985}
986
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000987bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
988 ASTContext &Context = TU->getASTContext();
989
990 // Some builtin types (such as Objective-C's "id", "sel", and
991 // "Class") have associated declarations. Create cursors for those.
992 QualType VisitType;
993 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000994 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000995 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000996 case BuiltinType::Char_U:
997 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000998 case BuiltinType::Char16:
999 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001000 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001001 case BuiltinType::UInt:
1002 case BuiltinType::ULong:
1003 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001004 case BuiltinType::UInt128:
1005 case BuiltinType::Char_S:
1006 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001007 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001008 case BuiltinType::Short:
1009 case BuiltinType::Int:
1010 case BuiltinType::Long:
1011 case BuiltinType::LongLong:
1012 case BuiltinType::Int128:
1013 case BuiltinType::Float:
1014 case BuiltinType::Double:
1015 case BuiltinType::LongDouble:
1016 case BuiltinType::NullPtr:
1017 case BuiltinType::Overload:
1018 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001019 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001020
1021 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001022 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001023
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001024 case BuiltinType::ObjCId:
1025 VisitType = Context.getObjCIdType();
1026 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001027
1028 case BuiltinType::ObjCClass:
1029 VisitType = Context.getObjCClassType();
1030 break;
1031
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001032 case BuiltinType::ObjCSel:
1033 VisitType = Context.getObjCSelType();
1034 break;
1035 }
1036
1037 if (!VisitType.isNull()) {
1038 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001039 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001040 TU));
1041 }
1042
1043 return false;
1044}
1045
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001046bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1047 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1048}
1049
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001050bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1051 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1052}
1053
1054bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1055 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1056}
1057
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001058bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1059 // FIXME: We can't visit the template template parameter, but there's
1060 // no context information with which we can match up the depth/index in the
1061 // type to the appropriate
1062 return false;
1063}
1064
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001065bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1066 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1067 return true;
1068
John McCallc12c5bb2010-05-15 11:32:37 +00001069 return false;
1070}
1071
1072bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1073 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1074 return true;
1075
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001076 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1077 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1078 TU)))
1079 return true;
1080 }
1081
1082 return false;
1083}
1084
1085bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001086 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001087}
1088
1089bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1090 return Visit(TL.getPointeeLoc());
1091}
1092
1093bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1094 return Visit(TL.getPointeeLoc());
1095}
1096
1097bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1098 return Visit(TL.getPointeeLoc());
1099}
1100
1101bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001102 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001103}
1104
1105bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001106 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001107}
1108
Douglas Gregor01829d32010-08-31 14:41:23 +00001109bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1110 bool SkipResultType) {
1111 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001112 return true;
1113
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001114 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001115 if (Decl *D = TL.getArg(I))
1116 if (Visit(MakeCXCursor(D, TU)))
1117 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001118
1119 return false;
1120}
1121
1122bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1123 if (Visit(TL.getElementLoc()))
1124 return true;
1125
1126 if (Expr *Size = TL.getSizeExpr())
1127 return Visit(MakeCXCursor(Size, StmtParent, TU));
1128
1129 return false;
1130}
1131
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001132bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1133 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001134 // Visit the template name.
1135 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1136 TL.getTemplateNameLoc()))
1137 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001138
1139 // Visit the template arguments.
1140 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1141 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1142 return true;
1143
1144 return false;
1145}
1146
Douglas Gregor2332c112010-01-21 20:48:56 +00001147bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1148 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1149}
1150
1151bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1152 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1153 return Visit(TSInfo->getTypeLoc());
1154
1155 return false;
1156}
1157
Douglas Gregora59e3902010-01-21 23:27:09 +00001158bool CursorVisitor::VisitStmt(Stmt *S) {
1159 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1160 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001161 if (Stmt *C = *Child)
1162 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1163 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001164 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001165
Douglas Gregora59e3902010-01-21 23:27:09 +00001166 return false;
1167}
1168
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001169bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1170 // Specially handle CaseStmts because they can be nested, e.g.:
1171 //
1172 // case 1:
1173 // case 2:
1174 //
1175 // In this case the second CaseStmt is the child of the first. Walking
1176 // these recursively can blow out the stack.
1177 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1178 while (true) {
1179 // Set the Parent field to Cursor, then back to its old value once we're
1180 // done.
1181 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1182
1183 if (Stmt *LHS = S->getLHS())
1184 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1185 return true;
1186 if (Stmt *RHS = S->getRHS())
1187 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1188 return true;
1189 if (Stmt *SubStmt = S->getSubStmt()) {
1190 if (!isa<CaseStmt>(SubStmt))
1191 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1192
1193 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1194 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1195 Cursor = MakeCXCursor(CS, StmtParent, TU);
1196 if (RegionOfInterest.isValid()) {
1197 SourceRange Range = CS->getSourceRange();
1198 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1199 return false;
1200 }
1201
1202 switch (Visitor(Cursor, Parent, ClientData)) {
1203 case CXChildVisit_Break: return true;
1204 case CXChildVisit_Continue: return false;
1205 case CXChildVisit_Recurse:
1206 // Perform tail-recursion manually.
1207 S = CS;
1208 continue;
1209 }
1210 }
1211 return false;
1212 }
1213}
1214
Douglas Gregora59e3902010-01-21 23:27:09 +00001215bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1216 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1217 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001218 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001219 return true;
1220 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001221
Douglas Gregora59e3902010-01-21 23:27:09 +00001222 return false;
1223}
1224
Douglas Gregorf5bab412010-01-22 01:00:11 +00001225bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1226 if (VarDecl *Var = S->getConditionVariable()) {
1227 if (Visit(MakeCXCursor(Var, TU)))
1228 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001229 }
1230
Douglas Gregor263b47b2010-01-25 16:12:32 +00001231 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1232 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001233 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1234 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001235 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1236 return true;
1237
1238 return false;
1239}
1240
1241bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1242 if (VarDecl *Var = S->getConditionVariable()) {
1243 if (Visit(MakeCXCursor(Var, TU)))
1244 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001245 }
1246
Douglas Gregor263b47b2010-01-25 16:12:32 +00001247 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1248 return true;
1249 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1250 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001251
Douglas Gregor263b47b2010-01-25 16:12:32 +00001252 return false;
1253}
1254
1255bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1256 if (VarDecl *Var = S->getConditionVariable()) {
1257 if (Visit(MakeCXCursor(Var, TU)))
1258 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001259 }
1260
Douglas Gregor263b47b2010-01-25 16:12:32 +00001261 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1262 return true;
1263 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001264 return true;
1265
Douglas Gregor263b47b2010-01-25 16:12:32 +00001266 return false;
1267}
1268
1269bool CursorVisitor::VisitForStmt(ForStmt *S) {
1270 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1271 return true;
1272 if (VarDecl *Var = S->getConditionVariable()) {
1273 if (Visit(MakeCXCursor(Var, TU)))
1274 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001275 }
1276
Douglas Gregor263b47b2010-01-25 16:12:32 +00001277 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1278 return true;
1279 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1280 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001281 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1282 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001283
Douglas Gregorf5bab412010-01-22 01:00:11 +00001284 return false;
1285}
1286
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001287bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1288 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1289 return true;
1290
1291 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1292 return true;
1293
1294 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1295 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1296 return true;
1297
1298 return false;
1299}
1300
Ted Kremenek3064ef92010-08-27 21:34:58 +00001301bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1302 if (D->isDefinition()) {
1303 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1304 E = D->bases_end(); I != E; ++I) {
1305 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1306 return true;
1307 }
1308 }
1309
1310 return VisitTagDecl(D);
1311}
1312
1313
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001314bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1315 return Visit(B->getBlockDecl());
1316}
1317
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001318bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1319 // FIXME: Visit fields as well?
1320 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1321 return true;
1322
1323 return VisitExpr(E);
1324}
1325
Douglas Gregor336fd812010-01-23 00:40:08 +00001326bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1327 if (E->isArgumentType()) {
1328 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1329 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001330
Douglas Gregor336fd812010-01-23 00:40:08 +00001331 return false;
1332 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001333
Douglas Gregor336fd812010-01-23 00:40:08 +00001334 return VisitExpr(E);
1335}
1336
1337bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1338 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
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 VisitCastExpr(E);
1343}
1344
1345bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1346 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1347 if (Visit(TSInfo->getTypeLoc()))
1348 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001349
Douglas Gregor336fd812010-01-23 00:40:08 +00001350 return VisitExpr(E);
1351}
1352
Douglas Gregor648220e2010-08-10 15:02:34 +00001353bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1354 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1355 Visit(E->getArgTInfo2()->getTypeLoc());
1356}
1357
1358bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1359 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1360 return true;
1361
1362 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1363}
1364
Douglas Gregorc2350e52010-03-08 16:40:19 +00001365bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001366 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1367 if (Visit(TSInfo->getTypeLoc()))
1368 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001369
1370 return VisitExpr(E);
1371}
1372
Douglas Gregor81d34662010-04-20 15:39:42 +00001373bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1374 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1375}
1376
1377
Ted Kremenek09dfa372010-02-18 05:46:33 +00001378bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001379 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1380 i != e; ++i)
1381 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001382 return true;
1383
1384 return false;
1385}
1386
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001387extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001388CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1389 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001390 // We use crash recovery to make some of our APIs more reliable, implicitly
1391 // enable it.
1392 llvm::CrashRecoveryContext::Enable();
1393
Douglas Gregora030b7c2010-01-22 20:35:53 +00001394 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001395 if (excludeDeclarationsFromPCH)
1396 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001397 if (displayDiagnostics)
1398 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001399 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001400}
1401
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001402void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001403 if (CIdx)
1404 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001405 if (getenv("LIBCLANG_TIMING"))
1406 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001407}
1408
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001409void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001410 if (CIdx) {
1411 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1412 CXXIdx->setUseExternalASTGeneration(value);
1413 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001414}
1415
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001416CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001417 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001418 if (!CIdx)
1419 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001420
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001421 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001422
Douglas Gregor28019772010-04-05 23:52:57 +00001423 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001424 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001425 CXXIdx->getOnlyLocalDecls(),
1426 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001427}
1428
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001429unsigned clang_defaultEditingTranslationUnitOptions() {
1430 return CXTranslationUnit_PrecompiledPreamble;
1431}
1432
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001433CXTranslationUnit
1434clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1435 const char *source_filename,
1436 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001437 const char **command_line_args,
1438 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001439 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001440 return clang_parseTranslationUnit(CIdx, source_filename,
1441 command_line_args, num_command_line_args,
1442 unsaved_files, num_unsaved_files,
1443 CXTranslationUnit_DetailedPreprocessingRecord);
1444}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001445
1446struct ParseTranslationUnitInfo {
1447 CXIndex CIdx;
1448 const char *source_filename;
1449 const char **command_line_args;
1450 int num_command_line_args;
1451 struct CXUnsavedFile *unsaved_files;
1452 unsigned num_unsaved_files;
1453 unsigned options;
1454 CXTranslationUnit result;
1455};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001456static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001457 ParseTranslationUnitInfo *PTUI =
1458 static_cast<ParseTranslationUnitInfo*>(UserData);
1459 CXIndex CIdx = PTUI->CIdx;
1460 const char *source_filename = PTUI->source_filename;
1461 const char **command_line_args = PTUI->command_line_args;
1462 int num_command_line_args = PTUI->num_command_line_args;
1463 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1464 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1465 unsigned options = PTUI->options;
1466 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001467
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001468 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001469 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001470
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001471 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1472
Douglas Gregor44c181a2010-07-23 00:33:23 +00001473 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001474 bool CompleteTranslationUnit
1475 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001476 bool CacheCodeCompetionResults
1477 = options & CXTranslationUnit_CacheCompletionResults;
1478
Douglas Gregor5352ac02010-01-28 00:27:43 +00001479 // Configure the diagnostics.
1480 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001481 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1482 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001483
Douglas Gregor4db64a42010-01-23 00:14:00 +00001484 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1485 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001486 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001487 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001488 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001489 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1490 Buffer));
1491 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001492
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001493 if (!CXXIdx->getUseExternalASTGeneration()) {
1494 llvm::SmallVector<const char *, 16> Args;
1495
1496 // The 'source_filename' argument is optional. If the caller does not
1497 // specify it then it is assumed that the source file is specified
1498 // in the actual argument list.
1499 if (source_filename)
1500 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001501
1502 // Since the Clang C library is primarily used by batch tools dealing with
1503 // (often very broken) source code, where spell-checking can have a
1504 // significant negative impact on performance (particularly when
1505 // precompiled headers are involved), we disable it by default.
1506 // Note that we place this argument early in the list, so that it can be
1507 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001508 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001509
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001510 Args.insert(Args.end(), command_line_args,
1511 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001512
Douglas Gregor44c181a2010-07-23 00:33:23 +00001513 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001514 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1515 Args.push_back("-Xclang");
1516 Args.push_back("-detailed-preprocessing-record");
1517 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001518
Douglas Gregor5352ac02010-01-28 00:27:43 +00001519 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001520
Ted Kremenek29b72842010-01-07 22:49:05 +00001521#ifdef USE_CRASHTRACER
1522 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001523#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001524
Daniel Dunbar94220972009-12-05 02:17:18 +00001525 llvm::OwningPtr<ASTUnit> Unit(
1526 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001527 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001528 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001529 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001530 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001531 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001532 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001533 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001534 CompleteTranslationUnit,
1535 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001536
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001537 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001538 // Make sure to check that 'Unit' is non-NULL.
1539 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001540 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1541 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001542 D != DEnd; ++D) {
1543 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001544 CXString Msg = clang_formatDiagnostic(&Diag,
1545 clang_defaultDiagnosticDisplayOptions());
1546 fprintf(stderr, "%s\n", clang_getCString(Msg));
1547 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001548 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001549#ifdef LLVM_ON_WIN32
1550 // On Windows, force a flush, since there may be multiple copies of
1551 // stderr and stdout in the file system, all with different buffers
1552 // but writing to the same device.
1553 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001554#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001555 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001556 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001557
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001558 PTUI->result = Unit.take();
1559 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001560 }
1561
Ted Kremenek139ba862009-10-22 00:03:57 +00001562 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001563 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001564
Ted Kremenek139ba862009-10-22 00:03:57 +00001565 // First add the complete path to the 'clang' executable.
1566 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001567 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001568
Ted Kremenek139ba862009-10-22 00:03:57 +00001569 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001570 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001571
Ted Kremenek139ba862009-10-22 00:03:57 +00001572 // The 'source_filename' argument is optional. If the caller does not
1573 // specify it then it is assumed that the source file is specified
1574 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001575 if (source_filename)
1576 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001577
Steve Naroff37b5ac22009-10-15 20:50:09 +00001578 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001579 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001580 char astTmpFile[L_tmpnam];
1581 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001582
1583 // Since the Clang C library is primarily used by batch tools dealing with
1584 // (often very broken) source code, where spell-checking can have a
1585 // significant negative impact on performance (particularly when
1586 // precompiled headers are involved), we disable it by default.
1587 // Note that we place this argument early in the list, so that it can be
1588 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001589 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001590
Douglas Gregor4db64a42010-01-23 00:14:00 +00001591 // Remap any unsaved files to temporary files.
1592 std::vector<llvm::sys::Path> TemporaryFiles;
1593 std::vector<std::string> RemapArgs;
1594 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001595 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001596
Douglas Gregor4db64a42010-01-23 00:14:00 +00001597 // The pointers into the elements of RemapArgs are stable because we
1598 // won't be adding anything to RemapArgs after this point.
1599 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1600 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001601
Ted Kremenek139ba862009-10-22 00:03:57 +00001602 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1603 for (int i = 0; i < num_command_line_args; ++i)
1604 if (const char *arg = command_line_args[i]) {
1605 if (strcmp(arg, "-o") == 0) {
1606 ++i; // Also skip the matching argument.
1607 continue;
1608 }
1609 if (strcmp(arg, "-emit-ast") == 0 ||
1610 strcmp(arg, "-c") == 0 ||
1611 strcmp(arg, "-fsyntax-only") == 0) {
1612 continue;
1613 }
1614
1615 // Keep the argument.
1616 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001617 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001618
Douglas Gregord93256e2010-01-28 06:00:51 +00001619 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001620 char tmpFileResults[L_tmpnam];
1621 char *tmpResultsFileName = tmpnam(tmpFileResults);
1622 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001623 TemporaryFiles.push_back(DiagnosticsFile);
1624 argv.push_back("-fdiagnostics-binary");
1625
Douglas Gregor44c181a2010-07-23 00:33:23 +00001626 // Do we need the detailed preprocessing record?
1627 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1628 argv.push_back("-Xclang");
1629 argv.push_back("-detailed-preprocessing-record");
1630 }
1631
Ted Kremenek139ba862009-10-22 00:03:57 +00001632 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001633 argv.push_back(NULL);
1634
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001635 // Invoke 'clang'.
1636 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1637 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001638 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001639 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1640 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001641 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001642 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001643 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001644
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001645 if (!ErrMsg.empty()) {
1646 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001647 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001648 I != E; ++I) {
1649 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001650 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001651 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001652 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001653
Daniel Dunbar32141c82010-02-23 20:23:45 +00001654 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001655 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001656
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001657 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001658 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001659 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001660 RemappedFiles.size(),
1661 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001662 if (ATU) {
1663 LoadSerializedDiagnostics(DiagnosticsFile,
1664 num_unsaved_files, unsaved_files,
1665 ATU->getFileManager(),
1666 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001667 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001668 } else if (CXXIdx->getDisplayDiagnostics()) {
1669 // We failed to load the ASTUnit, but we can still deserialize the
1670 // diagnostics and emit them.
1671 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001672 Diagnostic Diag;
1673 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001674 // FIXME: Faked LangOpts!
1675 LangOptions LangOpts;
1676 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1677 LoadSerializedDiagnostics(DiagnosticsFile,
1678 num_unsaved_files, unsaved_files,
1679 FileMgr, SourceMgr, Diags);
1680 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1681 DEnd = Diags.end();
1682 D != DEnd; ++D) {
1683 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001684 CXString Msg = clang_formatDiagnostic(&Diag,
1685 clang_defaultDiagnosticDisplayOptions());
1686 fprintf(stderr, "%s\n", clang_getCString(Msg));
1687 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001688 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001689
1690#ifdef LLVM_ON_WIN32
1691 // On Windows, force a flush, since there may be multiple copies of
1692 // stderr and stdout in the file system, all with different buffers
1693 // but writing to the same device.
1694 fflush(stderr);
1695#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001696 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001697
Douglas Gregor313e26c2010-02-18 23:35:40 +00001698 if (ATU) {
1699 // Make the translation unit responsible for destroying all temporary files.
1700 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1701 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001702 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001703 } else {
1704 // Destroy all of the temporary files now; they can't be referenced any
1705 // longer.
1706 llvm::sys::Path(astTmpFile).eraseFromDisk();
1707 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1708 TemporaryFiles[i].eraseFromDisk();
1709 }
1710
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001711 PTUI->result = ATU;
1712}
1713CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1714 const char *source_filename,
1715 const char **command_line_args,
1716 int num_command_line_args,
1717 struct CXUnsavedFile *unsaved_files,
1718 unsigned num_unsaved_files,
1719 unsigned options) {
1720 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1721 num_command_line_args, unsaved_files, num_unsaved_files,
1722 options, 0 };
1723 llvm::CrashRecoveryContext CRC;
1724
1725 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001726 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1727 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1728 fprintf(stderr, " 'command_line_args' : [");
1729 for (int i = 0; i != num_command_line_args; ++i) {
1730 if (i)
1731 fprintf(stderr, ", ");
1732 fprintf(stderr, "'%s'", command_line_args[i]);
1733 }
1734 fprintf(stderr, "],\n");
1735 fprintf(stderr, " 'unsaved_files' : [");
1736 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1737 if (i)
1738 fprintf(stderr, ", ");
1739 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1740 unsaved_files[i].Length);
1741 }
1742 fprintf(stderr, "],\n");
1743 fprintf(stderr, " 'options' : %d,\n", options);
1744 fprintf(stderr, "}\n");
1745
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001746 return 0;
1747 }
1748
1749 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001750}
1751
Douglas Gregor19998442010-08-13 15:35:05 +00001752unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1753 return CXSaveTranslationUnit_None;
1754}
1755
1756int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1757 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001758 if (!TU)
1759 return 1;
1760
1761 return static_cast<ASTUnit *>(TU)->Save(FileName);
1762}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001763
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001764void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001765 if (CTUnit) {
1766 // If the translation unit has been marked as unsafe to free, just discard
1767 // it.
1768 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1769 return;
1770
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001771 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001772 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001773}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001774
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001775unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1776 return CXReparse_None;
1777}
1778
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001779struct ReparseTranslationUnitInfo {
1780 CXTranslationUnit TU;
1781 unsigned num_unsaved_files;
1782 struct CXUnsavedFile *unsaved_files;
1783 unsigned options;
1784 int result;
1785};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001786static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001787 ReparseTranslationUnitInfo *RTUI =
1788 static_cast<ReparseTranslationUnitInfo*>(UserData);
1789 CXTranslationUnit TU = RTUI->TU;
1790 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1791 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1792 unsigned options = RTUI->options;
1793 (void) options;
1794 RTUI->result = 1;
1795
Douglas Gregorabc563f2010-07-19 21:46:24 +00001796 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001797 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001798
1799 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1800 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1801 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1802 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001803 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001804 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1805 Buffer));
1806 }
1807
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001808 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1809 RemappedFiles.size()))
1810 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001811}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001812int clang_reparseTranslationUnit(CXTranslationUnit TU,
1813 unsigned num_unsaved_files,
1814 struct CXUnsavedFile *unsaved_files,
1815 unsigned options) {
1816 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1817 options, 0 };
1818 llvm::CrashRecoveryContext CRC;
1819
1820 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001821 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001822 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1823 return 1;
1824 }
1825
1826 return RTUI.result;
1827}
1828
Douglas Gregordf95a132010-08-09 20:45:32 +00001829
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001830CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001831 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001832 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001833
Steve Naroff77accc12009-09-03 18:19:54 +00001834 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001835 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001836}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001837
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001838CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001839 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001840 return Result;
1841}
1842
Ted Kremenekfb480492010-01-13 21:46:36 +00001843} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001844
Ted Kremenekfb480492010-01-13 21:46:36 +00001845//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001846// CXSourceLocation and CXSourceRange Operations.
1847//===----------------------------------------------------------------------===//
1848
Douglas Gregorb9790342010-01-22 21:44:22 +00001849extern "C" {
1850CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001851 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001852 return Result;
1853}
1854
1855unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001856 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1857 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1858 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001859}
1860
1861CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1862 CXFile file,
1863 unsigned line,
1864 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001865 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001866 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001867
Douglas Gregorb9790342010-01-22 21:44:22 +00001868 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1869 SourceLocation SLoc
1870 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001871 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001872 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001873
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001874 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001875}
1876
Douglas Gregor5352ac02010-01-28 00:27:43 +00001877CXSourceRange clang_getNullRange() {
1878 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1879 return Result;
1880}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001881
Douglas Gregor5352ac02010-01-28 00:27:43 +00001882CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1883 if (begin.ptr_data[0] != end.ptr_data[0] ||
1884 begin.ptr_data[1] != end.ptr_data[1])
1885 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001886
1887 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001888 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001889 return Result;
1890}
1891
Douglas Gregor46766dc2010-01-26 19:19:08 +00001892void clang_getInstantiationLocation(CXSourceLocation location,
1893 CXFile *file,
1894 unsigned *line,
1895 unsigned *column,
1896 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001897 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1898
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001899 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001900 if (file)
1901 *file = 0;
1902 if (line)
1903 *line = 0;
1904 if (column)
1905 *column = 0;
1906 if (offset)
1907 *offset = 0;
1908 return;
1909 }
1910
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001911 const SourceManager &SM =
1912 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001913 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001914
1915 if (file)
1916 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1917 if (line)
1918 *line = SM.getInstantiationLineNumber(InstLoc);
1919 if (column)
1920 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001921 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001922 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001923}
1924
Douglas Gregor1db19de2010-01-19 21:36:55 +00001925CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001926 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001927 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001928 return Result;
1929}
1930
1931CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001932 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001933 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001934 return Result;
1935}
1936
Douglas Gregorb9790342010-01-22 21:44:22 +00001937} // end: extern "C"
1938
Douglas Gregor1db19de2010-01-19 21:36:55 +00001939//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001940// CXFile Operations.
1941//===----------------------------------------------------------------------===//
1942
1943extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001944CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001945 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001946 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001947
Steve Naroff88145032009-10-27 14:35:18 +00001948 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001949 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001950}
1951
1952time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001953 if (!SFile)
1954 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001955
Steve Naroff88145032009-10-27 14:35:18 +00001956 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1957 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001958}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001959
Douglas Gregorb9790342010-01-22 21:44:22 +00001960CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1961 if (!tu)
1962 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001963
Douglas Gregorb9790342010-01-22 21:44:22 +00001964 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001965
Douglas Gregorb9790342010-01-22 21:44:22 +00001966 FileManager &FMgr = CXXUnit->getFileManager();
1967 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1968 return const_cast<FileEntry *>(File);
1969}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001970
Ted Kremenekfb480492010-01-13 21:46:36 +00001971} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001972
Ted Kremenekfb480492010-01-13 21:46:36 +00001973//===----------------------------------------------------------------------===//
1974// CXCursor Operations.
1975//===----------------------------------------------------------------------===//
1976
Ted Kremenekfb480492010-01-13 21:46:36 +00001977static Decl *getDeclFromExpr(Stmt *E) {
1978 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1979 return RefExpr->getDecl();
1980 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1981 return ME->getMemberDecl();
1982 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1983 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001984
Ted Kremenekfb480492010-01-13 21:46:36 +00001985 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1986 return getDeclFromExpr(CE->getCallee());
1987 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1988 return getDeclFromExpr(CE->getSubExpr());
1989 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1990 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001991
Ted Kremenekfb480492010-01-13 21:46:36 +00001992 return 0;
1993}
1994
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001995static SourceLocation getLocationFromExpr(Expr *E) {
1996 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1997 return /*FIXME:*/Msg->getLeftLoc();
1998 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1999 return DRE->getLocation();
2000 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2001 return Member->getMemberLoc();
2002 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2003 return Ivar->getLocation();
2004 return E->getLocStart();
2005}
2006
Ted Kremenekfb480492010-01-13 21:46:36 +00002007extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002008
2009unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002010 CXCursorVisitor visitor,
2011 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002012 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002013
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002014 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2015 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002016 return CursorVis.VisitChildren(parent);
2017}
2018
Douglas Gregor78205d42010-01-20 21:45:58 +00002019static CXString getDeclSpelling(Decl *D) {
2020 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2021 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002022 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002023
Douglas Gregor78205d42010-01-20 21:45:58 +00002024 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002025 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002026
Douglas Gregor78205d42010-01-20 21:45:58 +00002027 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2028 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2029 // and returns different names. NamedDecl returns the class name and
2030 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002031 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002032
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002033 if (isa<UsingDirectiveDecl>(D))
2034 return createCXString("");
2035
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002036 llvm::SmallString<1024> S;
2037 llvm::raw_svector_ostream os(S);
2038 ND->printName(os);
2039
2040 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002041}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002042
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002043CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002044 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002045 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002046
Steve Narofff334b4e2009-09-02 18:26:48 +00002047 if (clang_isReference(C.kind)) {
2048 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002049 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002050 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002051 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002052 }
2053 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002054 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002055 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002056 }
2057 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002058 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002059 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002060 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002061 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002062 case CXCursor_CXXBaseSpecifier: {
2063 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2064 return createCXString(B->getType().getAsString());
2065 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002066 case CXCursor_TypeRef: {
2067 TypeDecl *Type = getCursorTypeRef(C).first;
2068 assert(Type && "Missing type decl");
2069
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002070 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2071 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002072 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002073 case CXCursor_TemplateRef: {
2074 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002075 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002076
2077 return createCXString(Template->getNameAsString());
2078 }
Douglas Gregor69319002010-08-31 23:48:11 +00002079
2080 case CXCursor_NamespaceRef: {
2081 NamedDecl *NS = getCursorNamespaceRef(C).first;
2082 assert(NS && "Missing namespace decl");
2083
2084 return createCXString(NS->getNameAsString());
2085 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002086
Daniel Dunbaracca7252009-11-30 20:42:49 +00002087 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002088 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002089 }
2090 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002091
2092 if (clang_isExpression(C.kind)) {
2093 Decl *D = getDeclFromExpr(getCursorExpr(C));
2094 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002095 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002096 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002097 }
2098
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002099 if (C.kind == CXCursor_MacroInstantiation)
2100 return createCXString(getCursorMacroInstantiation(C)->getName()
2101 ->getNameStart());
2102
Douglas Gregor572feb22010-03-18 18:04:21 +00002103 if (C.kind == CXCursor_MacroDefinition)
2104 return createCXString(getCursorMacroDefinition(C)->getName()
2105 ->getNameStart());
2106
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002107 if (clang_isDeclaration(C.kind))
2108 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002109
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002110 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002111}
2112
Ted Kremeneke68fff62010-02-17 00:41:32 +00002113CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002114 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002115 case CXCursor_FunctionDecl:
2116 return createCXString("FunctionDecl");
2117 case CXCursor_TypedefDecl:
2118 return createCXString("TypedefDecl");
2119 case CXCursor_EnumDecl:
2120 return createCXString("EnumDecl");
2121 case CXCursor_EnumConstantDecl:
2122 return createCXString("EnumConstantDecl");
2123 case CXCursor_StructDecl:
2124 return createCXString("StructDecl");
2125 case CXCursor_UnionDecl:
2126 return createCXString("UnionDecl");
2127 case CXCursor_ClassDecl:
2128 return createCXString("ClassDecl");
2129 case CXCursor_FieldDecl:
2130 return createCXString("FieldDecl");
2131 case CXCursor_VarDecl:
2132 return createCXString("VarDecl");
2133 case CXCursor_ParmDecl:
2134 return createCXString("ParmDecl");
2135 case CXCursor_ObjCInterfaceDecl:
2136 return createCXString("ObjCInterfaceDecl");
2137 case CXCursor_ObjCCategoryDecl:
2138 return createCXString("ObjCCategoryDecl");
2139 case CXCursor_ObjCProtocolDecl:
2140 return createCXString("ObjCProtocolDecl");
2141 case CXCursor_ObjCPropertyDecl:
2142 return createCXString("ObjCPropertyDecl");
2143 case CXCursor_ObjCIvarDecl:
2144 return createCXString("ObjCIvarDecl");
2145 case CXCursor_ObjCInstanceMethodDecl:
2146 return createCXString("ObjCInstanceMethodDecl");
2147 case CXCursor_ObjCClassMethodDecl:
2148 return createCXString("ObjCClassMethodDecl");
2149 case CXCursor_ObjCImplementationDecl:
2150 return createCXString("ObjCImplementationDecl");
2151 case CXCursor_ObjCCategoryImplDecl:
2152 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002153 case CXCursor_CXXMethod:
2154 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002155 case CXCursor_UnexposedDecl:
2156 return createCXString("UnexposedDecl");
2157 case CXCursor_ObjCSuperClassRef:
2158 return createCXString("ObjCSuperClassRef");
2159 case CXCursor_ObjCProtocolRef:
2160 return createCXString("ObjCProtocolRef");
2161 case CXCursor_ObjCClassRef:
2162 return createCXString("ObjCClassRef");
2163 case CXCursor_TypeRef:
2164 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002165 case CXCursor_TemplateRef:
2166 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002167 case CXCursor_NamespaceRef:
2168 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002169 case CXCursor_UnexposedExpr:
2170 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002171 case CXCursor_BlockExpr:
2172 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002173 case CXCursor_DeclRefExpr:
2174 return createCXString("DeclRefExpr");
2175 case CXCursor_MemberRefExpr:
2176 return createCXString("MemberRefExpr");
2177 case CXCursor_CallExpr:
2178 return createCXString("CallExpr");
2179 case CXCursor_ObjCMessageExpr:
2180 return createCXString("ObjCMessageExpr");
2181 case CXCursor_UnexposedStmt:
2182 return createCXString("UnexposedStmt");
2183 case CXCursor_InvalidFile:
2184 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002185 case CXCursor_InvalidCode:
2186 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002187 case CXCursor_NoDeclFound:
2188 return createCXString("NoDeclFound");
2189 case CXCursor_NotImplemented:
2190 return createCXString("NotImplemented");
2191 case CXCursor_TranslationUnit:
2192 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002193 case CXCursor_UnexposedAttr:
2194 return createCXString("UnexposedAttr");
2195 case CXCursor_IBActionAttr:
2196 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002197 case CXCursor_IBOutletAttr:
2198 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002199 case CXCursor_IBOutletCollectionAttr:
2200 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002201 case CXCursor_PreprocessingDirective:
2202 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002203 case CXCursor_MacroDefinition:
2204 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002205 case CXCursor_MacroInstantiation:
2206 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002207 case CXCursor_Namespace:
2208 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002209 case CXCursor_LinkageSpec:
2210 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002211 case CXCursor_CXXBaseSpecifier:
2212 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002213 case CXCursor_Constructor:
2214 return createCXString("CXXConstructor");
2215 case CXCursor_Destructor:
2216 return createCXString("CXXDestructor");
2217 case CXCursor_ConversionFunction:
2218 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002219 case CXCursor_TemplateTypeParameter:
2220 return createCXString("TemplateTypeParameter");
2221 case CXCursor_NonTypeTemplateParameter:
2222 return createCXString("NonTypeTemplateParameter");
2223 case CXCursor_TemplateTemplateParameter:
2224 return createCXString("TemplateTemplateParameter");
2225 case CXCursor_FunctionTemplate:
2226 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002227 case CXCursor_ClassTemplate:
2228 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002229 case CXCursor_ClassTemplatePartialSpecialization:
2230 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002231 case CXCursor_NamespaceAlias:
2232 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002233 case CXCursor_UsingDirective:
2234 return createCXString("UsingDirective");
Steve Naroff89922f82009-08-31 00:59:03 +00002235 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002236
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002237 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002238 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002239}
Steve Naroff89922f82009-08-31 00:59:03 +00002240
Ted Kremeneke68fff62010-02-17 00:41:32 +00002241enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2242 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002243 CXClientData client_data) {
2244 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2245 *BestCursor = cursor;
2246 return CXChildVisit_Recurse;
2247}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002248
Douglas Gregorb9790342010-01-22 21:44:22 +00002249CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2250 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002251 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002252
Douglas Gregorb9790342010-01-22 21:44:22 +00002253 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002254 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2255
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002256 // Translate the given source location to make it point at the beginning of
2257 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002258 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002259
2260 // Guard against an invalid SourceLocation, or we may assert in one
2261 // of the following calls.
2262 if (SLoc.isInvalid())
2263 return clang_getNullCursor();
2264
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002265 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2266 CXXUnit->getASTContext().getLangOptions());
2267
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002268 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2269 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002270 // FIXME: Would be great to have a "hint" cursor, then walk from that
2271 // hint cursor upward until we find a cursor whose source range encloses
2272 // the region of interest, rather than starting from the translation unit.
2273 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002274 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002275 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002276 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002277 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002278 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002279}
2280
Ted Kremenek73885552009-11-17 19:28:59 +00002281CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002282 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002283}
2284
2285unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002286 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002287}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002288
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002289unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002290 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2291}
2292
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002293unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002294 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2295}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002296
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002297unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002298 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2299}
2300
Douglas Gregor97b98722010-01-19 23:20:36 +00002301unsigned clang_isExpression(enum CXCursorKind K) {
2302 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2303}
2304
2305unsigned clang_isStatement(enum CXCursorKind K) {
2306 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2307}
2308
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002309unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2310 return K == CXCursor_TranslationUnit;
2311}
2312
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002313unsigned clang_isPreprocessing(enum CXCursorKind K) {
2314 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2315}
2316
Ted Kremenekad6eff62010-03-08 21:17:29 +00002317unsigned clang_isUnexposed(enum CXCursorKind K) {
2318 switch (K) {
2319 case CXCursor_UnexposedDecl:
2320 case CXCursor_UnexposedExpr:
2321 case CXCursor_UnexposedStmt:
2322 case CXCursor_UnexposedAttr:
2323 return true;
2324 default:
2325 return false;
2326 }
2327}
2328
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002329CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002330 return C.kind;
2331}
2332
Douglas Gregor98258af2010-01-18 22:46:11 +00002333CXSourceLocation clang_getCursorLocation(CXCursor C) {
2334 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002335 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002336 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002337 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2338 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002339 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002340 }
2341
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002342 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002343 std::pair<ObjCProtocolDecl *, SourceLocation> P
2344 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002345 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002346 }
2347
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002348 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002349 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2350 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002351 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002352 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002353
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002354 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002355 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002356 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002357 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002358
2359 case CXCursor_TemplateRef: {
2360 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2361 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2362 }
2363
Douglas Gregor69319002010-08-31 23:48:11 +00002364 case CXCursor_NamespaceRef: {
2365 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2366 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2367 }
2368
Ted Kremenek3064ef92010-08-27 21:34:58 +00002369 case CXCursor_CXXBaseSpecifier: {
2370 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2371 return clang_getNullLocation();
2372 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002373
Douglas Gregorf46034a2010-01-18 23:41:10 +00002374 default:
2375 // FIXME: Need a way to enumerate all non-reference cases.
2376 llvm_unreachable("Missed a reference kind");
2377 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002378 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002379
2380 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002381 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002382 getLocationFromExpr(getCursorExpr(C)));
2383
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002384 if (C.kind == CXCursor_PreprocessingDirective) {
2385 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2386 return cxloc::translateSourceLocation(getCursorContext(C), L);
2387 }
Douglas Gregor48072312010-03-18 15:23:44 +00002388
2389 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002390 SourceLocation L
2391 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002392 return cxloc::translateSourceLocation(getCursorContext(C), L);
2393 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002394
2395 if (C.kind == CXCursor_MacroDefinition) {
2396 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2397 return cxloc::translateSourceLocation(getCursorContext(C), L);
2398 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002399
Ted Kremenek9a700d22010-05-12 06:16:13 +00002400 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002401 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002402
Douglas Gregorf46034a2010-01-18 23:41:10 +00002403 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002404 SourceLocation Loc = D->getLocation();
2405 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2406 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002407 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002408}
Douglas Gregora7bde202010-01-19 00:34:46 +00002409
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002410} // end extern "C"
2411
2412static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002413 if (clang_isReference(C.kind)) {
2414 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002415 case CXCursor_ObjCSuperClassRef:
2416 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002417
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002418 case CXCursor_ObjCProtocolRef:
2419 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002420
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002421 case CXCursor_ObjCClassRef:
2422 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002423
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002424 case CXCursor_TypeRef:
2425 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002426
2427 case CXCursor_TemplateRef:
2428 return getCursorTemplateRef(C).second;
2429
Douglas Gregor69319002010-08-31 23:48:11 +00002430 case CXCursor_NamespaceRef:
2431 return getCursorNamespaceRef(C).second;
2432
Ted Kremenek3064ef92010-08-27 21:34:58 +00002433 case CXCursor_CXXBaseSpecifier:
2434 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2435 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002436
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002437 default:
2438 // FIXME: Need a way to enumerate all non-reference cases.
2439 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002440 }
2441 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002442
2443 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002444 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002445
2446 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002447 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002448
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002449 if (C.kind == CXCursor_PreprocessingDirective)
2450 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002451
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002452 if (C.kind == CXCursor_MacroInstantiation)
2453 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002454
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002455 if (C.kind == CXCursor_MacroDefinition)
2456 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002457
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002458 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2459 return getCursorDecl(C)->getSourceRange();
2460
2461 return SourceRange();
2462}
2463
2464extern "C" {
2465
2466CXSourceRange clang_getCursorExtent(CXCursor C) {
2467 SourceRange R = getRawCursorExtent(C);
2468 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002469 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002470
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002471 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002472}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002473
2474CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002475 if (clang_isInvalid(C.kind))
2476 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002477
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002478 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002479 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002480 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002481
Douglas Gregor97b98722010-01-19 23:20:36 +00002482 if (clang_isExpression(C.kind)) {
2483 Decl *D = getDeclFromExpr(getCursorExpr(C));
2484 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002485 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002486 return clang_getNullCursor();
2487 }
2488
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002489 if (C.kind == CXCursor_MacroInstantiation) {
2490 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2491 return MakeMacroDefinitionCursor(Def, CXXUnit);
2492 }
2493
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002494 if (!clang_isReference(C.kind))
2495 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002496
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002497 switch (C.kind) {
2498 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002499 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002500
2501 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002502 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002503
2504 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002505 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002506
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002507 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002508 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002509
2510 case CXCursor_TemplateRef:
2511 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2512
Douglas Gregor69319002010-08-31 23:48:11 +00002513 case CXCursor_NamespaceRef:
2514 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2515
Ted Kremenek3064ef92010-08-27 21:34:58 +00002516 case CXCursor_CXXBaseSpecifier: {
2517 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2518 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2519 CXXUnit));
2520 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002521
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002522 default:
2523 // We would prefer to enumerate all non-reference cursor kinds here.
2524 llvm_unreachable("Unhandled reference cursor kind");
2525 break;
2526 }
2527 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002528
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002529 return clang_getNullCursor();
2530}
2531
Douglas Gregorb6998662010-01-19 19:34:47 +00002532CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002533 if (clang_isInvalid(C.kind))
2534 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002535
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002536 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002537
Douglas Gregorb6998662010-01-19 19:34:47 +00002538 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002539 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002540 C = clang_getCursorReferenced(C);
2541 WasReference = true;
2542 }
2543
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002544 if (C.kind == CXCursor_MacroInstantiation)
2545 return clang_getCursorReferenced(C);
2546
Douglas Gregorb6998662010-01-19 19:34:47 +00002547 if (!clang_isDeclaration(C.kind))
2548 return clang_getNullCursor();
2549
2550 Decl *D = getCursorDecl(C);
2551 if (!D)
2552 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002553
Douglas Gregorb6998662010-01-19 19:34:47 +00002554 switch (D->getKind()) {
2555 // Declaration kinds that don't really separate the notions of
2556 // declaration and definition.
2557 case Decl::Namespace:
2558 case Decl::Typedef:
2559 case Decl::TemplateTypeParm:
2560 case Decl::EnumConstant:
2561 case Decl::Field:
2562 case Decl::ObjCIvar:
2563 case Decl::ObjCAtDefsField:
2564 case Decl::ImplicitParam:
2565 case Decl::ParmVar:
2566 case Decl::NonTypeTemplateParm:
2567 case Decl::TemplateTemplateParm:
2568 case Decl::ObjCCategoryImpl:
2569 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002570 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002571 case Decl::LinkageSpec:
2572 case Decl::ObjCPropertyImpl:
2573 case Decl::FileScopeAsm:
2574 case Decl::StaticAssert:
2575 case Decl::Block:
2576 return C;
2577
2578 // Declaration kinds that don't make any sense here, but are
2579 // nonetheless harmless.
2580 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002581 break;
2582
2583 // Declaration kinds for which the definition is not resolvable.
2584 case Decl::UnresolvedUsingTypename:
2585 case Decl::UnresolvedUsingValue:
2586 break;
2587
2588 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002589 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2590 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002591
2592 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002593 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002594
2595 case Decl::Enum:
2596 case Decl::Record:
2597 case Decl::CXXRecord:
2598 case Decl::ClassTemplateSpecialization:
2599 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002600 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002601 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002602 return clang_getNullCursor();
2603
2604 case Decl::Function:
2605 case Decl::CXXMethod:
2606 case Decl::CXXConstructor:
2607 case Decl::CXXDestructor:
2608 case Decl::CXXConversion: {
2609 const FunctionDecl *Def = 0;
2610 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002611 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002612 return clang_getNullCursor();
2613 }
2614
2615 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002616 // Ask the variable if it has a definition.
2617 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2618 return MakeCXCursor(Def, CXXUnit);
2619 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002620 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002621
Douglas Gregorb6998662010-01-19 19:34:47 +00002622 case Decl::FunctionTemplate: {
2623 const FunctionDecl *Def = 0;
2624 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002625 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002626 return clang_getNullCursor();
2627 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002628
Douglas Gregorb6998662010-01-19 19:34:47 +00002629 case Decl::ClassTemplate: {
2630 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002631 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002632 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002633 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002634 return clang_getNullCursor();
2635 }
2636
2637 case Decl::Using: {
2638 UsingDecl *Using = cast<UsingDecl>(D);
2639 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002640 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2641 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002642 S != SEnd; ++S) {
2643 if (Def != clang_getNullCursor()) {
2644 // FIXME: We have no way to return multiple results.
2645 return clang_getNullCursor();
2646 }
2647
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002648 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002649 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002650 }
2651
2652 return Def;
2653 }
2654
2655 case Decl::UsingShadow:
2656 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002657 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002658 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002659
2660 case Decl::ObjCMethod: {
2661 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2662 if (Method->isThisDeclarationADefinition())
2663 return C;
2664
2665 // Dig out the method definition in the associated
2666 // @implementation, if we have it.
2667 // FIXME: The ASTs should make finding the definition easier.
2668 if (ObjCInterfaceDecl *Class
2669 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2670 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2671 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2672 Method->isInstanceMethod()))
2673 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002674 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002675
2676 return clang_getNullCursor();
2677 }
2678
2679 case Decl::ObjCCategory:
2680 if (ObjCCategoryImplDecl *Impl
2681 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002682 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002683 return clang_getNullCursor();
2684
2685 case Decl::ObjCProtocol:
2686 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2687 return C;
2688 return clang_getNullCursor();
2689
2690 case Decl::ObjCInterface:
2691 // There are two notions of a "definition" for an Objective-C
2692 // class: the interface and its implementation. When we resolved a
2693 // reference to an Objective-C class, produce the @interface as
2694 // the definition; when we were provided with the interface,
2695 // produce the @implementation as the definition.
2696 if (WasReference) {
2697 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2698 return C;
2699 } else if (ObjCImplementationDecl *Impl
2700 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002701 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002702 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002703
Douglas Gregorb6998662010-01-19 19:34:47 +00002704 case Decl::ObjCProperty:
2705 // FIXME: We don't really know where to find the
2706 // ObjCPropertyImplDecls that implement this property.
2707 return clang_getNullCursor();
2708
2709 case Decl::ObjCCompatibleAlias:
2710 if (ObjCInterfaceDecl *Class
2711 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2712 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002713 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002714
Douglas Gregorb6998662010-01-19 19:34:47 +00002715 return clang_getNullCursor();
2716
2717 case Decl::ObjCForwardProtocol: {
2718 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2719 if (Forward->protocol_size() == 1)
2720 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002721 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002722 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002723
2724 // FIXME: Cannot return multiple definitions.
2725 return clang_getNullCursor();
2726 }
2727
2728 case Decl::ObjCClass: {
2729 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2730 if (Class->size() == 1) {
2731 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2732 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002733 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002734 return clang_getNullCursor();
2735 }
2736
2737 // FIXME: Cannot return multiple definitions.
2738 return clang_getNullCursor();
2739 }
2740
2741 case Decl::Friend:
2742 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002743 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002744 return clang_getNullCursor();
2745
2746 case Decl::FriendTemplate:
2747 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002748 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002749 return clang_getNullCursor();
2750 }
2751
2752 return clang_getNullCursor();
2753}
2754
2755unsigned clang_isCursorDefinition(CXCursor C) {
2756 if (!clang_isDeclaration(C.kind))
2757 return 0;
2758
2759 return clang_getCursorDefinition(C) == C;
2760}
2761
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002762void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002763 const char **startBuf,
2764 const char **endBuf,
2765 unsigned *startLine,
2766 unsigned *startColumn,
2767 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002768 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002769 assert(getCursorDecl(C) && "CXCursor has null decl");
2770 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002771 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2772 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002773
Steve Naroff4ade6d62009-09-23 17:52:52 +00002774 SourceManager &SM = FD->getASTContext().getSourceManager();
2775 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2776 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2777 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2778 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2779 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2780 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2781}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002782
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002783void clang_enableStackTraces(void) {
2784 llvm::sys::PrintStackTraceOnErrorSignal();
2785}
2786
Ted Kremenekfb480492010-01-13 21:46:36 +00002787} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002788
Ted Kremenekfb480492010-01-13 21:46:36 +00002789//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002790// Token-based Operations.
2791//===----------------------------------------------------------------------===//
2792
2793/* CXToken layout:
2794 * int_data[0]: a CXTokenKind
2795 * int_data[1]: starting token location
2796 * int_data[2]: token length
2797 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002798 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002799 * otherwise unused.
2800 */
2801extern "C" {
2802
2803CXTokenKind clang_getTokenKind(CXToken CXTok) {
2804 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2805}
2806
2807CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2808 switch (clang_getTokenKind(CXTok)) {
2809 case CXToken_Identifier:
2810 case CXToken_Keyword:
2811 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002812 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2813 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002814
2815 case CXToken_Literal: {
2816 // We have stashed the starting pointer in the ptr_data field. Use it.
2817 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002818 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002819 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002820
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002821 case CXToken_Punctuation:
2822 case CXToken_Comment:
2823 break;
2824 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002825
2826 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002827 // deconstructing the source location.
2828 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2829 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002830 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002831
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002832 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2833 std::pair<FileID, unsigned> LocInfo
2834 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002835 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002836 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002837 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2838 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002839 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002840
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002841 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002842}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002843
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002844CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2845 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2846 if (!CXXUnit)
2847 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002848
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002849 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2850 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2851}
2852
2853CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2854 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002855 if (!CXXUnit)
2856 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002857
2858 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002859 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2860}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002861
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002862void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2863 CXToken **Tokens, unsigned *NumTokens) {
2864 if (Tokens)
2865 *Tokens = 0;
2866 if (NumTokens)
2867 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002868
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002869 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2870 if (!CXXUnit || !Tokens || !NumTokens)
2871 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002872
Douglas Gregorbdf60622010-03-05 21:16:25 +00002873 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2874
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002875 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002876 if (R.isInvalid())
2877 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002878
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002879 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2880 std::pair<FileID, unsigned> BeginLocInfo
2881 = SourceMgr.getDecomposedLoc(R.getBegin());
2882 std::pair<FileID, unsigned> EndLocInfo
2883 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002884
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002885 // Cannot tokenize across files.
2886 if (BeginLocInfo.first != EndLocInfo.first)
2887 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002888
2889 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002890 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002891 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002892 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002893 if (Invalid)
2894 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002895
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002896 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2897 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002898 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002899 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002900
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002901 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002902 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002903 llvm::SmallVector<CXToken, 32> CXTokens;
2904 Token Tok;
2905 do {
2906 // Lex the next token
2907 Lex.LexFromRawLexer(Tok);
2908 if (Tok.is(tok::eof))
2909 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002910
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002911 // Initialize the CXToken.
2912 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002913
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002914 // - Common fields
2915 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2916 CXTok.int_data[2] = Tok.getLength();
2917 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002918
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002919 // - Kind-specific fields
2920 if (Tok.isLiteral()) {
2921 CXTok.int_data[0] = CXToken_Literal;
2922 CXTok.ptr_data = (void *)Tok.getLiteralData();
2923 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002924 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002925 std::pair<FileID, unsigned> LocInfo
2926 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002927 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002928 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002929 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2930 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002931 return;
2932
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002933 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002934 IdentifierInfo *II
2935 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002936
2937 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2938 CXTok.int_data[0] = CXToken_Keyword;
2939 }
2940 else {
2941 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2942 CXToken_Identifier
2943 : CXToken_Keyword;
2944 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002945 CXTok.ptr_data = II;
2946 } else if (Tok.is(tok::comment)) {
2947 CXTok.int_data[0] = CXToken_Comment;
2948 CXTok.ptr_data = 0;
2949 } else {
2950 CXTok.int_data[0] = CXToken_Punctuation;
2951 CXTok.ptr_data = 0;
2952 }
2953 CXTokens.push_back(CXTok);
2954 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002955
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002956 if (CXTokens.empty())
2957 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002958
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002959 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2960 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2961 *NumTokens = CXTokens.size();
2962}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002963
Ted Kremenek6db61092010-05-05 00:55:15 +00002964void clang_disposeTokens(CXTranslationUnit TU,
2965 CXToken *Tokens, unsigned NumTokens) {
2966 free(Tokens);
2967}
2968
2969} // end: extern "C"
2970
2971//===----------------------------------------------------------------------===//
2972// Token annotation APIs.
2973//===----------------------------------------------------------------------===//
2974
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002975typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002976static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2977 CXCursor parent,
2978 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002979namespace {
2980class AnnotateTokensWorker {
2981 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002982 CXToken *Tokens;
2983 CXCursor *Cursors;
2984 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002985 unsigned TokIdx;
2986 CursorVisitor AnnotateVis;
2987 SourceManager &SrcMgr;
2988
2989 bool MoreTokens() const { return TokIdx < NumTokens; }
2990 unsigned NextToken() const { return TokIdx; }
2991 void AdvanceToken() { ++TokIdx; }
2992 SourceLocation GetTokenLoc(unsigned tokI) {
2993 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2994 }
2995
Ted Kremenek6db61092010-05-05 00:55:15 +00002996public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002997 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002998 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2999 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003000 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003001 NumTokens(numTokens), TokIdx(0),
3002 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3003 Decl::MaxPCHLevel, RegionOfInterest),
3004 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003005
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003006 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003007 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003008 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003009};
3010}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003011
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003012void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3013 // Walk the AST within the region of interest, annotating tokens
3014 // along the way.
3015 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003016
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003017 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3018 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3019 if (Pos != Annotated.end())
3020 Cursors[I] = Pos->second;
3021 }
3022
3023 // Finish up annotating any tokens left.
3024 if (!MoreTokens())
3025 return;
3026
3027 const CXCursor &C = clang_getNullCursor();
3028 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3029 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3030 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003031 }
3032}
3033
Ted Kremenek6db61092010-05-05 00:55:15 +00003034enum CXChildVisitResult
3035AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003036 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3037 // We can always annotate a preprocessing directive/macro instantiation.
3038 if (clang_isPreprocessing(cursor.kind)) {
3039 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003040 return CXChildVisit_Recurse;
3041 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003042
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003043 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003044
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003045 if (cursorRange.isInvalid())
3046 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003047
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003048 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3049
Ted Kremeneka333c662010-05-12 05:29:33 +00003050 // Adjust the annotated range based specific declarations.
3051 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3052 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003053 Decl *D = cxcursor::getCursorDecl(cursor);
3054 // Don't visit synthesized ObjC methods, since they have no syntatic
3055 // representation in the source.
3056 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3057 if (MD->isSynthesized())
3058 return CXChildVisit_Continue;
3059 }
3060 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003061 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3062 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003063 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003064 if (TLoc.isValid() &&
3065 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003066 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003067 }
3068 }
3069 }
3070
Ted Kremenek3f404602010-08-14 01:14:06 +00003071 // If the location of the cursor occurs within a macro instantiation, record
3072 // the spelling location of the cursor in our annotation map. We can then
3073 // paper over the token labelings during a post-processing step to try and
3074 // get cursor mappings for tokens that are the *arguments* of a macro
3075 // instantiation.
3076 if (L.isMacroID()) {
3077 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3078 // Only invalidate the old annotation if it isn't part of a preprocessing
3079 // directive. Here we assume that the default construction of CXCursor
3080 // results in CXCursor.kind being an initialized value (i.e., 0). If
3081 // this isn't the case, we can fix by doing lookup + insertion.
3082
3083 CXCursor &oldC = Annotated[rawEncoding];
3084 if (!clang_isPreprocessing(oldC.kind))
3085 oldC = cursor;
3086 }
3087
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003088 const enum CXCursorKind K = clang_getCursorKind(parent);
3089 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003090 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3091 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003092
3093 while (MoreTokens()) {
3094 const unsigned I = NextToken();
3095 SourceLocation TokLoc = GetTokenLoc(I);
3096 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3097 case RangeBefore:
3098 Cursors[I] = updateC;
3099 AdvanceToken();
3100 continue;
3101 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003102 case RangeOverlap:
3103 break;
3104 }
3105 break;
3106 }
3107
3108 // Visit children to get their cursor information.
3109 const unsigned BeforeChildren = NextToken();
3110 VisitChildren(cursor);
3111 const unsigned AfterChildren = NextToken();
3112
3113 // Adjust 'Last' to the last token within the extent of the cursor.
3114 while (MoreTokens()) {
3115 const unsigned I = NextToken();
3116 SourceLocation TokLoc = GetTokenLoc(I);
3117 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3118 case RangeBefore:
3119 assert(0 && "Infeasible");
3120 case RangeAfter:
3121 break;
3122 case RangeOverlap:
3123 Cursors[I] = updateC;
3124 AdvanceToken();
3125 continue;
3126 }
3127 break;
3128 }
3129 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003130
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003131 // Scan the tokens that are at the beginning of the cursor, but are not
3132 // capture by the child cursors.
3133
3134 // For AST elements within macros, rely on a post-annotate pass to
3135 // to correctly annotate the tokens with cursors. Otherwise we can
3136 // get confusing results of having tokens that map to cursors that really
3137 // are expanded by an instantiation.
3138 if (L.isMacroID())
3139 cursor = clang_getNullCursor();
3140
3141 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3142 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3143 break;
3144 Cursors[I] = cursor;
3145 }
3146 // Scan the tokens that are at the end of the cursor, but are not captured
3147 // but the child cursors.
3148 for (unsigned I = AfterChildren; I != Last; ++I)
3149 Cursors[I] = cursor;
3150
3151 TokIdx = Last;
3152 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003153}
3154
Ted Kremenek6db61092010-05-05 00:55:15 +00003155static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3156 CXCursor parent,
3157 CXClientData client_data) {
3158 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3159}
3160
3161extern "C" {
3162
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003163void clang_annotateTokens(CXTranslationUnit TU,
3164 CXToken *Tokens, unsigned NumTokens,
3165 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003166
3167 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003168 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003169
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003170 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003171 if (!CXXUnit) {
3172 // Any token we don't specifically annotate will have a NULL cursor.
3173 const CXCursor &C = clang_getNullCursor();
3174 for (unsigned I = 0; I != NumTokens; ++I)
3175 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003176 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003177 }
3178
Douglas Gregorbdf60622010-03-05 21:16:25 +00003179 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003180
Douglas Gregor0396f462010-03-19 05:22:59 +00003181 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003182 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003183 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3184 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003185 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3186 clang_getTokenLocation(TU,
3187 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003188
Douglas Gregor0396f462010-03-19 05:22:59 +00003189 // A mapping from the source locations found when re-lexing or traversing the
3190 // region of interest to the corresponding cursors.
3191 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003192
3193 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003194 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003195 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3196 std::pair<FileID, unsigned> BeginLocInfo
3197 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3198 std::pair<FileID, unsigned> EndLocInfo
3199 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003200
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003201 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003202 bool Invalid = false;
3203 if (BeginLocInfo.first == EndLocInfo.first &&
3204 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3205 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003206 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3207 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003208 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003209 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003210 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003211
3212 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003213 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003214 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003215 Token Tok;
3216 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003217
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003218 reprocess:
3219 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3220 // We have found a preprocessing directive. Gobble it up so that we
3221 // don't see it while preprocessing these tokens later, but keep track of
3222 // all of the token locations inside this preprocessing directive so that
3223 // we can annotate them appropriately.
3224 //
3225 // FIXME: Some simple tests here could identify macro definitions and
3226 // #undefs, to provide specific cursor kinds for those.
3227 std::vector<SourceLocation> Locations;
3228 do {
3229 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003230 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003231 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003232
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003233 using namespace cxcursor;
3234 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003235 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3236 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003237 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003238 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3239 Annotated[Locations[I].getRawEncoding()] = Cursor;
3240 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003241
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003242 if (Tok.isAtStartOfLine())
3243 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003244
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003245 continue;
3246 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003247
Douglas Gregor48072312010-03-18 15:23:44 +00003248 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003249 break;
3250 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003251 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003252
Douglas Gregor0396f462010-03-19 05:22:59 +00003253 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003254 // a specific cursor.
3255 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3256 CXXUnit, RegionOfInterest);
3257 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003258}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003259} // end: extern "C"
3260
3261//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003262// Operations for querying linkage of a cursor.
3263//===----------------------------------------------------------------------===//
3264
3265extern "C" {
3266CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003267 if (!clang_isDeclaration(cursor.kind))
3268 return CXLinkage_Invalid;
3269
Ted Kremenek16b42592010-03-03 06:36:57 +00003270 Decl *D = cxcursor::getCursorDecl(cursor);
3271 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3272 switch (ND->getLinkage()) {
3273 case NoLinkage: return CXLinkage_NoLinkage;
3274 case InternalLinkage: return CXLinkage_Internal;
3275 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3276 case ExternalLinkage: return CXLinkage_External;
3277 };
3278
3279 return CXLinkage_Invalid;
3280}
3281} // end: extern "C"
3282
3283//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003284// Operations for querying language of a cursor.
3285//===----------------------------------------------------------------------===//
3286
3287static CXLanguageKind getDeclLanguage(const Decl *D) {
3288 switch (D->getKind()) {
3289 default:
3290 break;
3291 case Decl::ImplicitParam:
3292 case Decl::ObjCAtDefsField:
3293 case Decl::ObjCCategory:
3294 case Decl::ObjCCategoryImpl:
3295 case Decl::ObjCClass:
3296 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003297 case Decl::ObjCForwardProtocol:
3298 case Decl::ObjCImplementation:
3299 case Decl::ObjCInterface:
3300 case Decl::ObjCIvar:
3301 case Decl::ObjCMethod:
3302 case Decl::ObjCProperty:
3303 case Decl::ObjCPropertyImpl:
3304 case Decl::ObjCProtocol:
3305 return CXLanguage_ObjC;
3306 case Decl::CXXConstructor:
3307 case Decl::CXXConversion:
3308 case Decl::CXXDestructor:
3309 case Decl::CXXMethod:
3310 case Decl::CXXRecord:
3311 case Decl::ClassTemplate:
3312 case Decl::ClassTemplatePartialSpecialization:
3313 case Decl::ClassTemplateSpecialization:
3314 case Decl::Friend:
3315 case Decl::FriendTemplate:
3316 case Decl::FunctionTemplate:
3317 case Decl::LinkageSpec:
3318 case Decl::Namespace:
3319 case Decl::NamespaceAlias:
3320 case Decl::NonTypeTemplateParm:
3321 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003322 case Decl::TemplateTemplateParm:
3323 case Decl::TemplateTypeParm:
3324 case Decl::UnresolvedUsingTypename:
3325 case Decl::UnresolvedUsingValue:
3326 case Decl::Using:
3327 case Decl::UsingDirective:
3328 case Decl::UsingShadow:
3329 return CXLanguage_CPlusPlus;
3330 }
3331
3332 return CXLanguage_C;
3333}
3334
3335extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003336
3337enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3338 if (clang_isDeclaration(cursor.kind))
3339 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3340 if (D->hasAttr<UnavailableAttr>() ||
3341 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3342 return CXAvailability_Available;
3343
3344 if (D->hasAttr<DeprecatedAttr>())
3345 return CXAvailability_Deprecated;
3346 }
3347
3348 return CXAvailability_Available;
3349}
3350
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003351CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3352 if (clang_isDeclaration(cursor.kind))
3353 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3354
3355 return CXLanguage_Invalid;
3356}
3357} // end: extern "C"
3358
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003359
3360//===----------------------------------------------------------------------===//
3361// C++ AST instrospection.
3362//===----------------------------------------------------------------------===//
3363
3364extern "C" {
3365unsigned clang_CXXMethod_isStatic(CXCursor C) {
3366 if (!clang_isDeclaration(C.kind))
3367 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003368
3369 CXXMethodDecl *Method = 0;
3370 Decl *D = cxcursor::getCursorDecl(C);
3371 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3372 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3373 else
3374 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3375 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003376}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003377
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003378} // end: extern "C"
3379
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003380//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003381// Attribute introspection.
3382//===----------------------------------------------------------------------===//
3383
3384extern "C" {
3385CXType clang_getIBOutletCollectionType(CXCursor C) {
3386 if (C.kind != CXCursor_IBOutletCollectionAttr)
3387 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3388
3389 IBOutletCollectionAttr *A =
3390 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3391
3392 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3393}
3394} // end: extern "C"
3395
3396//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003397// CXString Operations.
3398//===----------------------------------------------------------------------===//
3399
3400extern "C" {
3401const char *clang_getCString(CXString string) {
3402 return string.Spelling;
3403}
3404
3405void clang_disposeString(CXString string) {
3406 if (string.MustFreeString && string.Spelling)
3407 free((void*)string.Spelling);
3408}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003409
Ted Kremenekfb480492010-01-13 21:46:36 +00003410} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003411
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003412namespace clang { namespace cxstring {
3413CXString createCXString(const char *String, bool DupString){
3414 CXString Str;
3415 if (DupString) {
3416 Str.Spelling = strdup(String);
3417 Str.MustFreeString = 1;
3418 } else {
3419 Str.Spelling = String;
3420 Str.MustFreeString = 0;
3421 }
3422 return Str;
3423}
3424
3425CXString createCXString(llvm::StringRef String, bool DupString) {
3426 CXString Result;
3427 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3428 char *Spelling = (char *)malloc(String.size() + 1);
3429 memmove(Spelling, String.data(), String.size());
3430 Spelling[String.size()] = 0;
3431 Result.Spelling = Spelling;
3432 Result.MustFreeString = 1;
3433 } else {
3434 Result.Spelling = String.data();
3435 Result.MustFreeString = 0;
3436 }
3437 return Result;
3438}
3439}}
3440
Ted Kremenek04bb7162010-01-22 22:44:15 +00003441//===----------------------------------------------------------------------===//
3442// Misc. utility functions.
3443//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003444
Ted Kremenek04bb7162010-01-22 22:44:15 +00003445extern "C" {
3446
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003447CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003448 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003449}
3450
3451} // end: extern "C"