blob: 57367dd1596f71743bb83b429f3edf49e32e4928 [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"
Douglas Gregora67e03f2010-09-09 21:42:20 +000033#include "llvm/ADT/STLExtras.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000034#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor02465752009-10-16 21:24:31 +000035#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000036#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000037#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000038#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000039#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000040#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000041#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000042
Benjamin Kramerc2a98162010-03-13 21:22:49 +000043// Needed to define L_TMPNAM on some systems.
44#include <cstdio>
45
Steve Naroff50398192009-08-28 15:28:48 +000046using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000047using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000048using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000049
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000050//===----------------------------------------------------------------------===//
51// Crash Reporting.
52//===----------------------------------------------------------------------===//
53
Ted Kremenekd7ffd082010-05-22 00:06:46 +000054#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000055#include "clang/Analysis/Support/SaveAndRestore.h"
56// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000057static const char *__crashreporter_info__ = 0;
58asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000059#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000060static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000061static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000062static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
63static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
64
65static unsigned SetCrashTracerInfo(const char *str,
66 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000067
Ted Kremenek254ba7c2010-01-07 23:13:53 +000068 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000069 while (crashtracer_strings[slot]) {
70 if (++slot == NUM_CRASH_STRINGS)
71 slot = 0;
72 }
73 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000074 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000075
76 // We need to create an aggregate string because multiple threads
77 // may be in this method at one time. The crash reporter string
78 // will attempt to overapproximate the set of in-flight invocations
79 // of this function. Race conditions can still cause this goal
80 // to not be achieved.
81 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000082 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000083 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
84 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
85 }
86 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
87 return slot;
88}
89
90static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000091 unsigned max_slot = 0;
92 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000093
Ted Kremenek254ba7c2010-01-07 23:13:53 +000094 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
95
96 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
97 if (agg_crashtracer_strings[i] &&
98 crashtracer_counter_id[i] > max_value) {
99 max_slot = i;
100 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +0000101 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +0000102
103 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +0000104}
105
106namespace {
107class ArgsCrashTracerInfo {
108 llvm::SmallString<1024> CrashString;
109 llvm::SmallString<1024> AggregateString;
110 unsigned crashtracerSlot;
111public:
112 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
113 : crashtracerSlot(0)
114 {
115 {
116 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000117 Out << "ClangCIndex [" << getClangFullVersion() << "]"
118 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000119 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
120 E=Args.end(); I!=E; ++I)
121 Out << ' ' << *I;
122 }
123 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
124 AggregateString);
125 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000126
Ted Kremenek29b72842010-01-07 22:49:05 +0000127 ~ArgsCrashTracerInfo() {
128 ResetCrashTracerInfo(crashtracerSlot);
129 }
130};
131}
132#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000133
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000134/// \brief The result of comparing two source ranges.
135enum RangeComparisonResult {
136 /// \brief Either the ranges overlap or one of the ranges is invalid.
137 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000138
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000139 /// \brief The first range ends before the second range starts.
140 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000141
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000142 /// \brief The first range starts after the second range ends.
143 RangeAfter
144};
145
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000146/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000147/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000148static RangeComparisonResult RangeCompare(SourceManager &SM,
149 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000150 SourceRange R2) {
151 assert(R1.isValid() && "First range is invalid?");
152 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000153 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000154 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000155 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000156 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000157 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000158 return RangeAfter;
159 return RangeOverlap;
160}
161
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000162/// \brief Determine if a source location falls within, before, or after a
163/// a given source range.
164static RangeComparisonResult LocationCompare(SourceManager &SM,
165 SourceLocation L, SourceRange R) {
166 assert(R.isValid() && "First range is invalid?");
167 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000168 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000169 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000170 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
171 return RangeBefore;
172 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
173 return RangeAfter;
174 return RangeOverlap;
175}
176
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000177/// \brief Translate a Clang source range into a CIndex source range.
178///
179/// Clang internally represents ranges where the end location points to the
180/// start of the token at the end. However, for external clients it is more
181/// useful to have a CXSourceRange be a proper half-open interval. This routine
182/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000183CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000184 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000185 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000186 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000187 // location accordingly.
188 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000189 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000190 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000191 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000192 EndLoc = EndLoc.getFileLocWithOffset(Length);
193 }
194
195 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
196 R.getBegin().getRawEncoding(),
197 EndLoc.getRawEncoding() };
198 return Result;
199}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000200
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000201//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000202// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000203//===----------------------------------------------------------------------===//
204
Steve Naroff89922f82009-08-31 00:59:03 +0000205namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000206
Douglas Gregorb1373d02010-01-20 20:59:29 +0000207// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000208class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000209 public TypeLocVisitor<CursorVisitor, bool>,
210 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000211{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000212 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000213 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000215 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000216 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000217
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 /// \brief The declaration that serves at the parent of any statement or
219 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000220 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000221
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000222 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000223 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000224
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000225 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000226 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000227
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000228 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
229 // to the visitor. Declarations with a PCH level greater than this value will
230 // be suppressed.
231 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000232
233 /// \brief When valid, a source range to which the cursor should restrict
234 /// its search.
235 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000236
Douglas Gregorb1373d02010-01-20 20:59:29 +0000237 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000238 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000239 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000240
241 /// \brief Determine whether this particular source range comes before, comes
242 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000243 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000244 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000245 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
246
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000247 class SetParentRAII {
248 CXCursor &Parent;
249 Decl *&StmtParent;
250 CXCursor OldParent;
251
252 public:
253 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
254 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
255 {
256 Parent = NewParent;
257 if (clang_isDeclaration(Parent.kind))
258 StmtParent = getCursorDecl(Parent);
259 }
260
261 ~SetParentRAII() {
262 Parent = OldParent;
263 if (clang_isDeclaration(Parent.kind))
264 StmtParent = getCursorDecl(Parent);
265 }
266 };
267
Steve Naroff89922f82009-08-31 00:59:03 +0000268public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000269 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
270 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000271 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000272 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000273 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000274 {
275 Parent.kind = CXCursor_NoDeclFound;
276 Parent.data[0] = 0;
277 Parent.data[1] = 0;
278 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000279 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000280 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000281
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000282 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000283
284 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
285 getPreprocessedEntities();
286
Douglas Gregorb1373d02010-01-20 20:59:29 +0000287 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000288
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000289 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000290 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000291 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000292 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000293 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000294 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
295 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000296 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000297 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000298 bool VisitClassTemplatePartialSpecializationDecl(
299 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000300 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000301 bool VisitEnumConstantDecl(EnumConstantDecl *D);
302 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
303 bool VisitFunctionDecl(FunctionDecl *ND);
304 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000305 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000306 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000307 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000308 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000309 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000310 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
311 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
312 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
313 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000314 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000315 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
316 bool VisitObjCImplDecl(ObjCImplDecl *D);
317 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
318 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000319 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
320 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
321 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000322 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000323 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000324 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000325 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000326 bool VisitUsingDecl(UsingDecl *D);
327 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
328 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000329
Douglas Gregor01829d32010-08-31 14:41:23 +0000330 // Name visitor
331 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000332 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000333
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000334 // Template visitors
335 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000336 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000337 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
338
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000339 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000340 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000341 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000342 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000343 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
344 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000345 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000346 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000347 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000348 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
349 bool VisitPointerTypeLoc(PointerTypeLoc TL);
350 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
351 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
352 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
353 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000354 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000355 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000356 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000357 // FIXME: Implement visitors here when the unimplemented TypeLocs get
358 // implemented
359 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
360 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000361
Douglas Gregora59e3902010-01-21 23:27:09 +0000362 // Statement visitors
363 bool VisitStmt(Stmt *S);
364 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000365 bool VisitGotoStmt(GotoStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000366 bool VisitIfStmt(IfStmt *S);
367 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000368 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000369 bool VisitWhileStmt(WhileStmt *S);
370 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000371
Douglas Gregor336fd812010-01-23 00:40:08 +0000372 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000373 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000374 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000375 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000376 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000377 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000378 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000379 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000380 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000381 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfbb4c982010-09-02 21:07:44 +0000382 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000383 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000384 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
385 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000386 bool VisitInitListExpr(InitListExpr *E);
387 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000388 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000389 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000390 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000391 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
392 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000393 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000394 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000395 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000396 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000397 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000398 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000399 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000400 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000401};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000402
Ted Kremenekab188932010-01-05 19:32:54 +0000403} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000404
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000405static SourceRange getRawCursorExtent(CXCursor C);
406
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000407RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000408 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
409}
410
Douglas Gregorb1373d02010-01-20 20:59:29 +0000411/// \brief Visit the given cursor and, if requested by the visitor,
412/// its children.
413///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000414/// \param Cursor the cursor to visit.
415///
416/// \param CheckRegionOfInterest if true, then the caller already checked that
417/// this cursor is within the region of interest.
418///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000419/// \returns true if the visitation should be aborted, false if it
420/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000421bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000422 if (clang_isInvalid(Cursor.kind))
423 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000424
Douglas Gregorb1373d02010-01-20 20:59:29 +0000425 if (clang_isDeclaration(Cursor.kind)) {
426 Decl *D = getCursorDecl(Cursor);
427 assert(D && "Invalid declaration cursor");
428 if (D->getPCHLevel() > MaxPCHLevel)
429 return false;
430
431 if (D->isImplicit())
432 return false;
433 }
434
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000435 // If we have a range of interest, and this cursor doesn't intersect with it,
436 // we're done.
437 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000438 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000439 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000440 return false;
441 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000442
Douglas Gregorb1373d02010-01-20 20:59:29 +0000443 switch (Visitor(Cursor, Parent, ClientData)) {
444 case CXChildVisit_Break:
445 return true;
446
447 case CXChildVisit_Continue:
448 return false;
449
450 case CXChildVisit_Recurse:
451 return VisitChildren(Cursor);
452 }
453
Douglas Gregorfd643772010-01-25 16:45:46 +0000454 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000455}
456
Douglas Gregor788f5a12010-03-20 00:41:21 +0000457std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
458CursorVisitor::getPreprocessedEntities() {
459 PreprocessingRecord &PPRec
460 = *TU->getPreprocessor().getPreprocessingRecord();
461
462 bool OnlyLocalDecls
463 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
464
465 // There is no region of interest; we have to walk everything.
466 if (RegionOfInterest.isInvalid())
467 return std::make_pair(PPRec.begin(OnlyLocalDecls),
468 PPRec.end(OnlyLocalDecls));
469
470 // Find the file in which the region of interest lands.
471 SourceManager &SM = TU->getSourceManager();
472 std::pair<FileID, unsigned> Begin
473 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
474 std::pair<FileID, unsigned> End
475 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
476
477 // The region of interest spans files; we have to walk everything.
478 if (Begin.first != End.first)
479 return std::make_pair(PPRec.begin(OnlyLocalDecls),
480 PPRec.end(OnlyLocalDecls));
481
482 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
483 = TU->getPreprocessedEntitiesByFile();
484 if (ByFileMap.empty()) {
485 // Build the mapping from files to sets of preprocessed entities.
486 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
487 EEnd = PPRec.end(OnlyLocalDecls);
488 E != EEnd; ++E) {
489 std::pair<FileID, unsigned> P
490 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
491 ByFileMap[P.first].push_back(*E);
492 }
493 }
494
495 return std::make_pair(ByFileMap[Begin.first].begin(),
496 ByFileMap[Begin.first].end());
497}
498
Douglas Gregorb1373d02010-01-20 20:59:29 +0000499/// \brief Visit the children of the given cursor.
500///
501/// \returns true if the visitation should be aborted, false if it
502/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000503bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000504 if (clang_isReference(Cursor.kind)) {
505 // By definition, references have no children.
506 return false;
507 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000508
509 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000510 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000511 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000512
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 if (clang_isDeclaration(Cursor.kind)) {
514 Decl *D = getCursorDecl(Cursor);
515 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000516 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000517 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000518
Douglas Gregora59e3902010-01-21 23:27:09 +0000519 if (clang_isStatement(Cursor.kind))
520 return Visit(getCursorStmt(Cursor));
521 if (clang_isExpression(Cursor.kind))
522 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000523
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000525 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000526 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
527 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000528 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
529 TLEnd = CXXUnit->top_level_end();
530 TL != TLEnd; ++TL) {
531 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000532 return true;
533 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000534 } else if (VisitDeclContext(
535 CXXUnit->getASTContext().getTranslationUnitDecl()))
536 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000537
Douglas Gregor0396f462010-03-19 05:22:59 +0000538 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000539 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000540 // FIXME: Once we have the ability to deserialize a preprocessing record,
541 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000542 PreprocessingRecord::iterator E, EEnd;
543 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000544 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
545 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
546 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000547
Douglas Gregor0396f462010-03-19 05:22:59 +0000548 continue;
549 }
550
551 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
552 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
553 return true;
554
555 continue;
556 }
557 }
558 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000559 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000560 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000561
Douglas Gregorb1373d02010-01-20 20:59:29 +0000562 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000563 return false;
564}
565
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000566bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000567 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
568 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000569
Ted Kremenek664cffd2010-07-22 11:30:19 +0000570 if (Stmt *Body = B->getBody())
571 return Visit(MakeCXCursor(Body, StmtParent, TU));
572
573 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000574}
575
Douglas Gregorb1373d02010-01-20 20:59:29 +0000576bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000577 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000578 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000579
Ted Kremenek23173d72010-05-18 21:09:07 +0000580 Decl *D = *I;
581 if (D->getLexicalDeclContext() != DC)
582 continue;
583
584 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000585
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000586 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000587 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000588 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000589 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000590
591 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000592 case RangeBefore:
593 // This declaration comes before the region of interest; skip it.
594 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000595
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000596 case RangeAfter:
597 // This declaration comes after the region of interest; we're done.
598 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000599
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000600 case RangeOverlap:
601 // This declaration overlaps the region of interest; visit it.
602 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000603 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000604 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000605
Daniel Dunbard52864b2010-02-14 10:02:57 +0000606 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000607 return true;
608 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000609
Douglas Gregorb1373d02010-01-20 20:59:29 +0000610 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000611}
612
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000613bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
614 llvm_unreachable("Translation units are visited directly by Visit()");
615 return false;
616}
617
618bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
619 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
620 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000621
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000622 return false;
623}
624
625bool CursorVisitor::VisitTagDecl(TagDecl *D) {
626 return VisitDeclContext(D);
627}
628
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000629bool CursorVisitor::VisitClassTemplateSpecializationDecl(
630 ClassTemplateSpecializationDecl *D) {
631 bool ShouldVisitBody = false;
632 switch (D->getSpecializationKind()) {
633 case TSK_Undeclared:
634 case TSK_ImplicitInstantiation:
635 // Nothing to visit
636 return false;
637
638 case TSK_ExplicitInstantiationDeclaration:
639 case TSK_ExplicitInstantiationDefinition:
640 break;
641
642 case TSK_ExplicitSpecialization:
643 ShouldVisitBody = true;
644 break;
645 }
646
647 // Visit the template arguments used in the specialization.
648 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
649 TypeLoc TL = SpecType->getTypeLoc();
650 if (TemplateSpecializationTypeLoc *TSTLoc
651 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
652 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
653 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
654 return true;
655 }
656 }
657
658 if (ShouldVisitBody && VisitCXXRecordDecl(D))
659 return true;
660
661 return false;
662}
663
Douglas Gregor74dbe642010-08-31 19:31:58 +0000664bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
665 ClassTemplatePartialSpecializationDecl *D) {
666 // FIXME: Visit the "outer" template parameter lists on the TagDecl
667 // before visiting these template parameters.
668 if (VisitTemplateParameters(D->getTemplateParameters()))
669 return true;
670
671 // Visit the partial specialization arguments.
672 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
673 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
674 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
675 return true;
676
677 return VisitCXXRecordDecl(D);
678}
679
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000680bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000681 // Visit the default argument.
682 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
683 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
684 if (Visit(DefArg->getTypeLoc()))
685 return true;
686
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000687 return false;
688}
689
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000690bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
691 if (Expr *Init = D->getInitExpr())
692 return Visit(MakeCXCursor(Init, StmtParent, TU));
693 return false;
694}
695
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000696bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
697 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
698 if (Visit(TSInfo->getTypeLoc()))
699 return true;
700
701 return false;
702}
703
Douglas Gregora67e03f2010-09-09 21:42:20 +0000704/// \brief Compare two base or member initializers based on their source order.
705static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
706 CXXBaseOrMemberInitializer const * const *X
707 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
708 CXXBaseOrMemberInitializer const * const *Y
709 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
710
711 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
712 return -1;
713 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
714 return 1;
715 else
716 return 0;
717}
718
Douglas Gregorb1373d02010-01-20 20:59:29 +0000719bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000720 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
721 // Visit the function declaration's syntactic components in the order
722 // written. This requires a bit of work.
723 TypeLoc TL = TSInfo->getTypeLoc();
724 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
725
726 // If we have a function declared directly (without the use of a typedef),
727 // visit just the return type. Otherwise, just visit the function's type
728 // now.
729 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
730 (!FTL && Visit(TL)))
731 return true;
732
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000733 // Visit the nested-name-specifier, if present.
734 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
735 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
736 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000737
738 // Visit the declaration name.
739 if (VisitDeclarationNameInfo(ND->getNameInfo()))
740 return true;
741
742 // FIXME: Visit explicitly-specified template arguments!
743
744 // Visit the function parameters, if we have a function type.
745 if (FTL && VisitFunctionTypeLoc(*FTL, true))
746 return true;
747
748 // FIXME: Attributes?
749 }
750
Douglas Gregora67e03f2010-09-09 21:42:20 +0000751 if (ND->isThisDeclarationADefinition()) {
752 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
753 // Find the initializers that were written in the source.
754 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
755 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
756 IEnd = Constructor->init_end();
757 I != IEnd; ++I) {
758 if (!(*I)->isWritten())
759 continue;
760
761 WrittenInits.push_back(*I);
762 }
763
764 // Sort the initializers in source order
765 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
766 &CompareCXXBaseOrMemberInitializers);
767
768 // Visit the initializers in source order
769 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
770 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
771 if (Init->isMemberInitializer()) {
772 if (Visit(MakeCursorMemberRef(Init->getMember(),
773 Init->getMemberLocation(), TU)))
774 return true;
775 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
776 if (Visit(BaseInfo->getTypeLoc()))
777 return true;
778 }
779
780 // Visit the initializer value.
781 if (Expr *Initializer = Init->getInit())
782 if (Visit(MakeCXCursor(Initializer, ND, TU)))
783 return true;
784 }
785 }
786
787 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
788 return true;
789 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000790
Douglas Gregorb1373d02010-01-20 20:59:29 +0000791 return false;
792}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000793
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000794bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
795 if (VisitDeclaratorDecl(D))
796 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000797
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000798 if (Expr *BitWidth = D->getBitWidth())
799 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000800
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000801 return false;
802}
803
804bool CursorVisitor::VisitVarDecl(VarDecl *D) {
805 if (VisitDeclaratorDecl(D))
806 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000807
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000808 if (Expr *Init = D->getInit())
809 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000810
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000811 return false;
812}
813
Douglas Gregor84b51d72010-09-01 20:16:53 +0000814bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
815 if (VisitDeclaratorDecl(D))
816 return true;
817
818 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
819 if (Expr *DefArg = D->getDefaultArgument())
820 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
821
822 return false;
823}
824
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000825bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
826 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
827 // before visiting these template parameters.
828 if (VisitTemplateParameters(D->getTemplateParameters()))
829 return true;
830
831 return VisitFunctionDecl(D->getTemplatedDecl());
832}
833
Douglas Gregor39d6f072010-08-31 19:02:00 +0000834bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
835 // FIXME: Visit the "outer" template parameter lists on the TagDecl
836 // before visiting these template parameters.
837 if (VisitTemplateParameters(D->getTemplateParameters()))
838 return true;
839
840 return VisitCXXRecordDecl(D->getTemplatedDecl());
841}
842
Douglas Gregor84b51d72010-09-01 20:16:53 +0000843bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
844 if (VisitTemplateParameters(D->getTemplateParameters()))
845 return true;
846
847 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
848 VisitTemplateArgumentLoc(D->getDefaultArgument()))
849 return true;
850
851 return false;
852}
853
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000855 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
856 if (Visit(TSInfo->getTypeLoc()))
857 return true;
858
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000859 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000860 PEnd = ND->param_end();
861 P != PEnd; ++P) {
862 if (Visit(MakeCXCursor(*P, TU)))
863 return true;
864 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000865
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000866 if (ND->isThisDeclarationADefinition() &&
867 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
868 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000869
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000870 return false;
871}
872
Douglas Gregora59e3902010-01-21 23:27:09 +0000873bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
874 return VisitDeclContext(D);
875}
876
Douglas Gregorb1373d02010-01-20 20:59:29 +0000877bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000878 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
879 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000880 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000881
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000882 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
883 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
884 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000885 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000886 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000887
Douglas Gregora59e3902010-01-21 23:27:09 +0000888 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000889}
890
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000891bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
892 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
893 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
894 E = PID->protocol_end(); I != E; ++I, ++PL)
895 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
896 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000897
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000898 return VisitObjCContainerDecl(PID);
899}
900
Ted Kremenek23173d72010-05-18 21:09:07 +0000901bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000902 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000903 return true;
904
Ted Kremenek23173d72010-05-18 21:09:07 +0000905 // FIXME: This implements a workaround with @property declarations also being
906 // installed in the DeclContext for the @interface. Eventually this code
907 // should be removed.
908 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
909 if (!CDecl || !CDecl->IsClassExtension())
910 return false;
911
912 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
913 if (!ID)
914 return false;
915
916 IdentifierInfo *PropertyId = PD->getIdentifier();
917 ObjCPropertyDecl *prevDecl =
918 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
919
920 if (!prevDecl)
921 return false;
922
923 // Visit synthesized methods since they will be skipped when visiting
924 // the @interface.
925 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000926 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000927 if (Visit(MakeCXCursor(MD, TU)))
928 return true;
929
930 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000931 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000932 if (Visit(MakeCXCursor(MD, TU)))
933 return true;
934
935 return false;
936}
937
Douglas Gregorb1373d02010-01-20 20:59:29 +0000938bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000939 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000940 if (D->getSuperClass() &&
941 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000942 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000943 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000944 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000945
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000946 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
947 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
948 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000949 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000950 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000951
Douglas Gregora59e3902010-01-21 23:27:09 +0000952 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000953}
954
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000955bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
956 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000957}
958
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000959bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000960 // 'ID' could be null when dealing with invalid code.
961 if (ObjCInterfaceDecl *ID = D->getClassInterface())
962 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
963 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000964
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000965 return VisitObjCImplDecl(D);
966}
967
968bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
969#if 0
970 // Issue callbacks for super class.
971 // FIXME: No source location information!
972 if (D->getSuperClass() &&
973 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000974 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000975 TU)))
976 return true;
977#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000978
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000979 return VisitObjCImplDecl(D);
980}
981
982bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
983 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
984 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
985 E = D->protocol_end();
986 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000987 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000988 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000989
990 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000991}
992
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000993bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
994 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
995 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
996 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000997
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000998 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000999}
1000
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001001bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1002 return VisitDeclContext(D);
1003}
1004
Douglas Gregor69319002010-08-31 23:48:11 +00001005bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001006 // Visit nested-name-specifier.
1007 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1008 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1009 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001010
1011 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1012 D->getTargetNameLoc(), TU));
1013}
1014
Douglas Gregor7e242562010-09-01 19:52:22 +00001015bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001016 // Visit nested-name-specifier.
1017 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1018 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1019 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001020
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001021 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1022 return true;
1023
Douglas Gregor7e242562010-09-01 19:52:22 +00001024 return VisitDeclarationNameInfo(D->getNameInfo());
1025}
1026
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001027bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001028 // Visit nested-name-specifier.
1029 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1030 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1031 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001032
1033 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1034 D->getIdentLocation(), TU));
1035}
1036
Douglas Gregor7e242562010-09-01 19:52:22 +00001037bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001038 // Visit nested-name-specifier.
1039 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1040 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1041 return true;
1042
Douglas Gregor7e242562010-09-01 19:52:22 +00001043 return VisitDeclarationNameInfo(D->getNameInfo());
1044}
1045
1046bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1047 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001048 // Visit nested-name-specifier.
1049 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1050 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1051 return true;
1052
Douglas Gregor7e242562010-09-01 19:52:22 +00001053 return false;
1054}
1055
Douglas Gregor01829d32010-08-31 14:41:23 +00001056bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1057 switch (Name.getName().getNameKind()) {
1058 case clang::DeclarationName::Identifier:
1059 case clang::DeclarationName::CXXLiteralOperatorName:
1060 case clang::DeclarationName::CXXOperatorName:
1061 case clang::DeclarationName::CXXUsingDirective:
1062 return false;
1063
1064 case clang::DeclarationName::CXXConstructorName:
1065 case clang::DeclarationName::CXXDestructorName:
1066 case clang::DeclarationName::CXXConversionFunctionName:
1067 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1068 return Visit(TSInfo->getTypeLoc());
1069 return false;
1070
1071 case clang::DeclarationName::ObjCZeroArgSelector:
1072 case clang::DeclarationName::ObjCOneArgSelector:
1073 case clang::DeclarationName::ObjCMultiArgSelector:
1074 // FIXME: Per-identifier location info?
1075 return false;
1076 }
1077
1078 return false;
1079}
1080
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001081bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1082 SourceRange Range) {
1083 // FIXME: This whole routine is a hack to work around the lack of proper
1084 // source information in nested-name-specifiers (PR5791). Since we do have
1085 // a beginning source location, we can visit the first component of the
1086 // nested-name-specifier, if it's a single-token component.
1087 if (!NNS)
1088 return false;
1089
1090 // Get the first component in the nested-name-specifier.
1091 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1092 NNS = Prefix;
1093
1094 switch (NNS->getKind()) {
1095 case NestedNameSpecifier::Namespace:
1096 // FIXME: The token at this source location might actually have been a
1097 // namespace alias, but we don't model that. Lame!
1098 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1099 TU));
1100
1101 case NestedNameSpecifier::TypeSpec: {
1102 // If the type has a form where we know that the beginning of the source
1103 // range matches up with a reference cursor. Visit the appropriate reference
1104 // cursor.
1105 Type *T = NNS->getAsType();
1106 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1107 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1108 if (const TagType *Tag = dyn_cast<TagType>(T))
1109 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1110 if (const TemplateSpecializationType *TST
1111 = dyn_cast<TemplateSpecializationType>(T))
1112 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1113 break;
1114 }
1115
1116 case NestedNameSpecifier::TypeSpecWithTemplate:
1117 case NestedNameSpecifier::Global:
1118 case NestedNameSpecifier::Identifier:
1119 break;
1120 }
1121
1122 return false;
1123}
1124
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001125bool CursorVisitor::VisitTemplateParameters(
1126 const TemplateParameterList *Params) {
1127 if (!Params)
1128 return false;
1129
1130 for (TemplateParameterList::const_iterator P = Params->begin(),
1131 PEnd = Params->end();
1132 P != PEnd; ++P) {
1133 if (Visit(MakeCXCursor(*P, TU)))
1134 return true;
1135 }
1136
1137 return false;
1138}
1139
Douglas Gregor0b36e612010-08-31 20:37:03 +00001140bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1141 switch (Name.getKind()) {
1142 case TemplateName::Template:
1143 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1144
1145 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001146 // Visit the overloaded template set.
1147 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1148 return true;
1149
Douglas Gregor0b36e612010-08-31 20:37:03 +00001150 return false;
1151
1152 case TemplateName::DependentTemplate:
1153 // FIXME: Visit nested-name-specifier.
1154 return false;
1155
1156 case TemplateName::QualifiedTemplate:
1157 // FIXME: Visit nested-name-specifier.
1158 return Visit(MakeCursorTemplateRef(
1159 Name.getAsQualifiedTemplateName()->getDecl(),
1160 Loc, TU));
1161 }
1162
1163 return false;
1164}
1165
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001166bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1167 switch (TAL.getArgument().getKind()) {
1168 case TemplateArgument::Null:
1169 case TemplateArgument::Integral:
1170 return false;
1171
1172 case TemplateArgument::Pack:
1173 // FIXME: Implement when variadic templates come along.
1174 return false;
1175
1176 case TemplateArgument::Type:
1177 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1178 return Visit(TSInfo->getTypeLoc());
1179 return false;
1180
1181 case TemplateArgument::Declaration:
1182 if (Expr *E = TAL.getSourceDeclExpression())
1183 return Visit(MakeCXCursor(E, StmtParent, TU));
1184 return false;
1185
1186 case TemplateArgument::Expression:
1187 if (Expr *E = TAL.getSourceExpression())
1188 return Visit(MakeCXCursor(E, StmtParent, TU));
1189 return false;
1190
1191 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001192 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1193 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001194 }
1195
1196 return false;
1197}
1198
Ted Kremeneka0536d82010-05-07 01:04:29 +00001199bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1200 return VisitDeclContext(D);
1201}
1202
Douglas Gregor01829d32010-08-31 14:41:23 +00001203bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1204 return Visit(TL.getUnqualifiedLoc());
1205}
1206
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001207bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1208 ASTContext &Context = TU->getASTContext();
1209
1210 // Some builtin types (such as Objective-C's "id", "sel", and
1211 // "Class") have associated declarations. Create cursors for those.
1212 QualType VisitType;
1213 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001214 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001215 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001216 case BuiltinType::Char_U:
1217 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001218 case BuiltinType::Char16:
1219 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001220 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001221 case BuiltinType::UInt:
1222 case BuiltinType::ULong:
1223 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001224 case BuiltinType::UInt128:
1225 case BuiltinType::Char_S:
1226 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001227 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001228 case BuiltinType::Short:
1229 case BuiltinType::Int:
1230 case BuiltinType::Long:
1231 case BuiltinType::LongLong:
1232 case BuiltinType::Int128:
1233 case BuiltinType::Float:
1234 case BuiltinType::Double:
1235 case BuiltinType::LongDouble:
1236 case BuiltinType::NullPtr:
1237 case BuiltinType::Overload:
1238 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001239 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001240
1241 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001242 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001243
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001244 case BuiltinType::ObjCId:
1245 VisitType = Context.getObjCIdType();
1246 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001247
1248 case BuiltinType::ObjCClass:
1249 VisitType = Context.getObjCClassType();
1250 break;
1251
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001252 case BuiltinType::ObjCSel:
1253 VisitType = Context.getObjCSelType();
1254 break;
1255 }
1256
1257 if (!VisitType.isNull()) {
1258 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001259 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001260 TU));
1261 }
1262
1263 return false;
1264}
1265
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001266bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1267 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1268}
1269
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001270bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1271 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1272}
1273
1274bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1275 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1276}
1277
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001278bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001279 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001280 // no context information with which we can match up the depth/index in the
1281 // type to the appropriate
1282 return false;
1283}
1284
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001285bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1286 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1287 return true;
1288
John McCallc12c5bb2010-05-15 11:32:37 +00001289 return false;
1290}
1291
1292bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1293 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1294 return true;
1295
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001296 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1297 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1298 TU)))
1299 return true;
1300 }
1301
1302 return false;
1303}
1304
1305bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001306 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001307}
1308
1309bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1310 return Visit(TL.getPointeeLoc());
1311}
1312
1313bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1314 return Visit(TL.getPointeeLoc());
1315}
1316
1317bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1318 return Visit(TL.getPointeeLoc());
1319}
1320
1321bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001322 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001323}
1324
1325bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001326 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001327}
1328
Douglas Gregor01829d32010-08-31 14:41:23 +00001329bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1330 bool SkipResultType) {
1331 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001332 return true;
1333
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001334 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001335 if (Decl *D = TL.getArg(I))
1336 if (Visit(MakeCXCursor(D, TU)))
1337 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001338
1339 return false;
1340}
1341
1342bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1343 if (Visit(TL.getElementLoc()))
1344 return true;
1345
1346 if (Expr *Size = TL.getSizeExpr())
1347 return Visit(MakeCXCursor(Size, StmtParent, TU));
1348
1349 return false;
1350}
1351
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001352bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1353 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001354 // Visit the template name.
1355 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1356 TL.getTemplateNameLoc()))
1357 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001358
1359 // Visit the template arguments.
1360 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1361 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1362 return true;
1363
1364 return false;
1365}
1366
Douglas Gregor2332c112010-01-21 20:48:56 +00001367bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1368 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1369}
1370
1371bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1372 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1373 return Visit(TSInfo->getTypeLoc());
1374
1375 return false;
1376}
1377
Douglas Gregora59e3902010-01-21 23:27:09 +00001378bool CursorVisitor::VisitStmt(Stmt *S) {
1379 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1380 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001381 if (Stmt *C = *Child)
1382 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1383 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001384 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001385
Douglas Gregora59e3902010-01-21 23:27:09 +00001386 return false;
1387}
1388
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001389bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1390 // Specially handle CaseStmts because they can be nested, e.g.:
1391 //
1392 // case 1:
1393 // case 2:
1394 //
1395 // In this case the second CaseStmt is the child of the first. Walking
1396 // these recursively can blow out the stack.
1397 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1398 while (true) {
1399 // Set the Parent field to Cursor, then back to its old value once we're
1400 // done.
1401 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1402
1403 if (Stmt *LHS = S->getLHS())
1404 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1405 return true;
1406 if (Stmt *RHS = S->getRHS())
1407 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1408 return true;
1409 if (Stmt *SubStmt = S->getSubStmt()) {
1410 if (!isa<CaseStmt>(SubStmt))
1411 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1412
1413 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1414 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1415 Cursor = MakeCXCursor(CS, StmtParent, TU);
1416 if (RegionOfInterest.isValid()) {
1417 SourceRange Range = CS->getSourceRange();
1418 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1419 return false;
1420 }
1421
1422 switch (Visitor(Cursor, Parent, ClientData)) {
1423 case CXChildVisit_Break: return true;
1424 case CXChildVisit_Continue: return false;
1425 case CXChildVisit_Recurse:
1426 // Perform tail-recursion manually.
1427 S = CS;
1428 continue;
1429 }
1430 }
1431 return false;
1432 }
1433}
1434
Douglas Gregora59e3902010-01-21 23:27:09 +00001435bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1436 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1437 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001438 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001439 return true;
1440 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001441
Douglas Gregora59e3902010-01-21 23:27:09 +00001442 return false;
1443}
1444
Douglas Gregor36897b02010-09-10 00:22:18 +00001445bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1446 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1447}
1448
Douglas Gregorf5bab412010-01-22 01:00:11 +00001449bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1450 if (VarDecl *Var = S->getConditionVariable()) {
1451 if (Visit(MakeCXCursor(Var, TU)))
1452 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001453 }
1454
Douglas Gregor263b47b2010-01-25 16:12:32 +00001455 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1456 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001457 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1458 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001459 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1460 return true;
1461
1462 return false;
1463}
1464
1465bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1466 if (VarDecl *Var = S->getConditionVariable()) {
1467 if (Visit(MakeCXCursor(Var, TU)))
1468 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001469 }
1470
Douglas Gregor263b47b2010-01-25 16:12:32 +00001471 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1472 return true;
1473 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1474 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001475
Douglas Gregor263b47b2010-01-25 16:12:32 +00001476 return false;
1477}
1478
1479bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1480 if (VarDecl *Var = S->getConditionVariable()) {
1481 if (Visit(MakeCXCursor(Var, TU)))
1482 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001483 }
1484
Douglas Gregor263b47b2010-01-25 16:12:32 +00001485 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1486 return true;
1487 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001488 return true;
1489
Douglas Gregor263b47b2010-01-25 16:12:32 +00001490 return false;
1491}
1492
1493bool CursorVisitor::VisitForStmt(ForStmt *S) {
1494 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1495 return true;
1496 if (VarDecl *Var = S->getConditionVariable()) {
1497 if (Visit(MakeCXCursor(Var, TU)))
1498 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001499 }
1500
Douglas Gregor263b47b2010-01-25 16:12:32 +00001501 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1502 return true;
1503 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1504 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001505 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1506 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001507
Douglas Gregorf5bab412010-01-22 01:00:11 +00001508 return false;
1509}
1510
Douglas Gregor8947a752010-09-02 20:35:02 +00001511bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1512 // Visit nested-name-specifier, if present.
1513 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1514 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1515 return true;
1516
1517 // Visit declaration name.
1518 if (VisitDeclarationNameInfo(E->getNameInfo()))
1519 return true;
1520
1521 // Visit explicitly-specified template arguments.
1522 if (E->hasExplicitTemplateArgs()) {
1523 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1524 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1525 *ArgEnd = Arg + Args.NumTemplateArgs;
1526 Arg != ArgEnd; ++Arg)
1527 if (VisitTemplateArgumentLoc(*Arg))
1528 return true;
1529 }
1530
1531 return false;
1532}
1533
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001534bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1535 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1536 return true;
1537
1538 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1539 return true;
1540
1541 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1542 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1543 return true;
1544
1545 return false;
1546}
1547
Ted Kremenek3064ef92010-08-27 21:34:58 +00001548bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1549 if (D->isDefinition()) {
1550 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1551 E = D->bases_end(); I != E; ++I) {
1552 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1553 return true;
1554 }
1555 }
1556
1557 return VisitTagDecl(D);
1558}
1559
1560
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001561bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1562 return Visit(B->getBlockDecl());
1563}
1564
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001565bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001566 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001567 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1568 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001569
1570 // Visit the components of the offsetof expression.
1571 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1572 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1573 const OffsetOfNode &Node = E->getComponent(I);
1574 switch (Node.getKind()) {
1575 case OffsetOfNode::Array:
1576 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1577 StmtParent, TU)))
1578 return true;
1579 break;
1580
1581 case OffsetOfNode::Field:
1582 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1583 TU)))
1584 return true;
1585 break;
1586
1587 case OffsetOfNode::Identifier:
1588 case OffsetOfNode::Base:
1589 continue;
1590 }
1591 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001592
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001593 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001594}
1595
Douglas Gregor336fd812010-01-23 00:40:08 +00001596bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1597 if (E->isArgumentType()) {
1598 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1599 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001600
Douglas Gregor336fd812010-01-23 00:40:08 +00001601 return false;
1602 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001603
Douglas Gregor336fd812010-01-23 00:40:08 +00001604 return VisitExpr(E);
1605}
1606
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001607bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1608 // Visit the base expression.
1609 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1610 return true;
1611
1612 // Visit the nested-name-specifier
1613 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1614 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1615 return true;
1616
1617 // Visit the declaration name.
1618 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1619 return true;
1620
1621 // Visit the explicitly-specified template arguments, if any.
1622 if (E->hasExplicitTemplateArgs()) {
1623 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1624 *ArgEnd = Arg + E->getNumTemplateArgs();
1625 Arg != ArgEnd;
1626 ++Arg) {
1627 if (VisitTemplateArgumentLoc(*Arg))
1628 return true;
1629 }
1630 }
1631
1632 return false;
1633}
1634
Douglas Gregor336fd812010-01-23 00:40:08 +00001635bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1636 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1637 if (Visit(TSInfo->getTypeLoc()))
1638 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001639
Douglas Gregor336fd812010-01-23 00:40:08 +00001640 return VisitCastExpr(E);
1641}
1642
1643bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1644 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1645 if (Visit(TSInfo->getTypeLoc()))
1646 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001647
Douglas Gregor336fd812010-01-23 00:40:08 +00001648 return VisitExpr(E);
1649}
1650
Douglas Gregor36897b02010-09-10 00:22:18 +00001651bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1652 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1653}
1654
Douglas Gregor648220e2010-08-10 15:02:34 +00001655bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1656 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1657 Visit(E->getArgTInfo2()->getTypeLoc());
1658}
1659
1660bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1661 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1662 return true;
1663
1664 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1665}
1666
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001667bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1668 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001669 if (InitListExpr *Syntactic = E->getSyntacticForm())
1670 return VisitExpr(Syntactic);
1671
1672 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001673}
1674
1675bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1676 // Visit the designators.
1677 typedef DesignatedInitExpr::Designator Designator;
1678 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1679 DEnd = E->designators_end();
1680 D != DEnd; ++D) {
1681 if (D->isFieldDesignator()) {
1682 if (FieldDecl *Field = D->getField())
1683 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1684 return true;
1685
1686 continue;
1687 }
1688
1689 if (D->isArrayDesignator()) {
1690 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1691 return true;
1692
1693 continue;
1694 }
1695
1696 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1697 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1698 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1699 return true;
1700 }
1701
1702 // Visit the initializer value itself.
1703 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1704}
1705
Douglas Gregor94802292010-09-02 21:20:16 +00001706bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1707 if (E->isTypeOperand()) {
1708 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1709 return Visit(TSInfo->getTypeLoc());
1710
1711 return false;
1712 }
1713
1714 return VisitExpr(E);
1715}
1716
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001717bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1718 if (E->isTypeOperand()) {
1719 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1720 return Visit(TSInfo->getTypeLoc());
1721
1722 return false;
1723 }
1724
1725 return VisitExpr(E);
1726}
1727
Douglas Gregorab6677e2010-09-08 00:15:04 +00001728bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1729 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1730 return Visit(TSInfo->getTypeLoc());
1731
1732 return VisitExpr(E);
1733}
1734
1735bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1736 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1737 return Visit(TSInfo->getTypeLoc());
1738
1739 return false;
1740}
1741
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001742bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1743 // Visit placement arguments.
1744 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1745 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1746 return true;
1747
1748 // Visit the allocated type.
1749 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1750 if (Visit(TSInfo->getTypeLoc()))
1751 return true;
1752
1753 // Visit the array size, if any.
1754 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1755 return true;
1756
1757 // Visit the initializer or constructor arguments.
1758 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1759 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1760 return true;
1761
1762 return false;
1763}
1764
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001765bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1766 // Visit base expression.
1767 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1768 return true;
1769
1770 // Visit the nested-name-specifier.
1771 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1772 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1773 return true;
1774
1775 // Visit the scope type that looks disturbingly like the nested-name-specifier
1776 // but isn't.
1777 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1778 if (Visit(TSInfo->getTypeLoc()))
1779 return true;
1780
1781 // Visit the name of the type being destroyed.
1782 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1783 if (Visit(TSInfo->getTypeLoc()))
1784 return true;
1785
1786 return false;
1787}
1788
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001789bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1790 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1791}
1792
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001793bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001794 // Visit the nested-name-specifier.
1795 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1796 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1797 return true;
1798
1799 // Visit the declaration name.
1800 if (VisitDeclarationNameInfo(E->getNameInfo()))
1801 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001802
1803 // Visit the overloaded declaration reference.
1804 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1805 return true;
1806
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001807 // Visit the explicitly-specified template arguments.
1808 if (const ExplicitTemplateArgumentList *ArgList
1809 = E->getOptionalExplicitTemplateArgs()) {
1810 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1811 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1812 Arg != ArgEnd; ++Arg) {
1813 if (VisitTemplateArgumentLoc(*Arg))
1814 return true;
1815 }
1816 }
1817
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001818 return false;
1819}
1820
Douglas Gregorbfebed22010-09-03 17:24:10 +00001821bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1822 DependentScopeDeclRefExpr *E) {
1823 // Visit the nested-name-specifier.
1824 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1825 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1826 return true;
1827
1828 // Visit the declaration name.
1829 if (VisitDeclarationNameInfo(E->getNameInfo()))
1830 return true;
1831
1832 // Visit the explicitly-specified template arguments.
1833 if (const ExplicitTemplateArgumentList *ArgList
1834 = E->getOptionalExplicitTemplateArgs()) {
1835 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1836 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1837 Arg != ArgEnd; ++Arg) {
1838 if (VisitTemplateArgumentLoc(*Arg))
1839 return true;
1840 }
1841 }
1842
1843 return false;
1844}
1845
Douglas Gregorab6677e2010-09-08 00:15:04 +00001846bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1847 CXXUnresolvedConstructExpr *E) {
1848 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1849 if (Visit(TSInfo->getTypeLoc()))
1850 return true;
1851
1852 return VisitExpr(E);
1853}
1854
Douglas Gregor25d63622010-09-03 17:35:34 +00001855bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1856 CXXDependentScopeMemberExpr *E) {
1857 // Visit the base expression, if there is one.
1858 if (!E->isImplicitAccess() &&
1859 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1860 return true;
1861
1862 // Visit the nested-name-specifier.
1863 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1864 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1865 return true;
1866
1867 // Visit the declaration name.
1868 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1869 return true;
1870
1871 // Visit the explicitly-specified template arguments.
1872 if (const ExplicitTemplateArgumentList *ArgList
1873 = E->getOptionalExplicitTemplateArgs()) {
1874 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1875 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1876 Arg != ArgEnd; ++Arg) {
1877 if (VisitTemplateArgumentLoc(*Arg))
1878 return true;
1879 }
1880 }
1881
1882 return false;
1883}
1884
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001885bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1886 // Visit the base expression, if there is one.
1887 if (!E->isImplicitAccess() &&
1888 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1889 return true;
1890
1891 return VisitOverloadExpr(E);
1892}
Douglas Gregor25d63622010-09-03 17:35:34 +00001893
Douglas Gregorc2350e52010-03-08 16:40:19 +00001894bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001895 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1896 if (Visit(TSInfo->getTypeLoc()))
1897 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001898
1899 return VisitExpr(E);
1900}
1901
Douglas Gregor81d34662010-04-20 15:39:42 +00001902bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1903 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1904}
1905
1906
Ted Kremenek09dfa372010-02-18 05:46:33 +00001907bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001908 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1909 i != e; ++i)
1910 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001911 return true;
1912
1913 return false;
1914}
1915
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001916static llvm::sys::Mutex EnableMultithreadingMutex;
1917static bool EnabledMultithreading;
1918
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001919extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001920CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1921 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001922 // We use crash recovery to make some of our APIs more reliable, implicitly
1923 // enable it.
1924 llvm::CrashRecoveryContext::Enable();
1925
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001926 // Enable support for multithreading in LLVM.
1927 {
1928 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
1929 if (!EnabledMultithreading) {
1930 llvm::llvm_start_multithreaded();
1931 EnabledMultithreading = true;
1932 }
1933 }
1934
Douglas Gregora030b7c2010-01-22 20:35:53 +00001935 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001936 if (excludeDeclarationsFromPCH)
1937 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001938 if (displayDiagnostics)
1939 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001940 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001941}
1942
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001943void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001944 if (CIdx)
1945 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001946}
1947
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001948void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001949 if (CIdx) {
1950 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1951 CXXIdx->setUseExternalASTGeneration(value);
1952 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001953}
1954
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001955CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001956 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001957 if (!CIdx)
1958 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001959
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001960 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001961
Douglas Gregor28019772010-04-05 23:52:57 +00001962 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001963 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001964 CXXIdx->getOnlyLocalDecls(),
1965 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001966}
1967
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001968unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00001969 return CXTranslationUnit_PrecompiledPreamble |
1970 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001971}
1972
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001973CXTranslationUnit
1974clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1975 const char *source_filename,
1976 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001977 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001978 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001979 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001980 return clang_parseTranslationUnit(CIdx, source_filename,
1981 command_line_args, num_command_line_args,
1982 unsaved_files, num_unsaved_files,
1983 CXTranslationUnit_DetailedPreprocessingRecord);
1984}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001985
1986struct ParseTranslationUnitInfo {
1987 CXIndex CIdx;
1988 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001989 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001990 int num_command_line_args;
1991 struct CXUnsavedFile *unsaved_files;
1992 unsigned num_unsaved_files;
1993 unsigned options;
1994 CXTranslationUnit result;
1995};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001996static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001997 ParseTranslationUnitInfo *PTUI =
1998 static_cast<ParseTranslationUnitInfo*>(UserData);
1999 CXIndex CIdx = PTUI->CIdx;
2000 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002001 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002002 int num_command_line_args = PTUI->num_command_line_args;
2003 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2004 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2005 unsigned options = PTUI->options;
2006 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002007
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002008 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002009 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002010
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002011 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2012
Douglas Gregor44c181a2010-07-23 00:33:23 +00002013 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002014 bool CompleteTranslationUnit
2015 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002016 bool CacheCodeCompetionResults
2017 = options & CXTranslationUnit_CacheCompletionResults;
2018
Douglas Gregor5352ac02010-01-28 00:27:43 +00002019 // Configure the diagnostics.
2020 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002021 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2022 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002023
Douglas Gregor4db64a42010-01-23 00:14:00 +00002024 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2025 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002026 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002027 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002028 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002029 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2030 Buffer));
2031 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002032
Daniel Dunbar8506dde2009-12-03 01:54:28 +00002033 if (!CXXIdx->getUseExternalASTGeneration()) {
2034 llvm::SmallVector<const char *, 16> Args;
2035
2036 // The 'source_filename' argument is optional. If the caller does not
2037 // specify it then it is assumed that the source file is specified
2038 // in the actual argument list.
2039 if (source_filename)
2040 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002041
2042 // Since the Clang C library is primarily used by batch tools dealing with
2043 // (often very broken) source code, where spell-checking can have a
2044 // significant negative impact on performance (particularly when
2045 // precompiled headers are involved), we disable it by default.
Douglas Gregorfe08e402010-10-02 20:06:51 +00002046 // Only do this if we haven't found a spell-checking-related argument.
2047 bool FoundSpellCheckingArgument = false;
2048 for (int I = 0; I != num_command_line_args; ++I) {
2049 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2050 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2051 FoundSpellCheckingArgument = true;
2052 break;
2053 }
2054 }
2055 if (!FoundSpellCheckingArgument)
2056 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002057
Daniel Dunbar8506dde2009-12-03 01:54:28 +00002058 Args.insert(Args.end(), command_line_args,
2059 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00002060
Douglas Gregor44c181a2010-07-23 00:33:23 +00002061 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00002062 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2063 Args.push_back("-Xclang");
2064 Args.push_back("-detailed-preprocessing-record");
2065 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00002066
Douglas Gregor5352ac02010-01-28 00:27:43 +00002067 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002068
Ted Kremenek29b72842010-01-07 22:49:05 +00002069#ifdef USE_CRASHTRACER
2070 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00002071#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002072
Daniel Dunbar94220972009-12-05 02:17:18 +00002073 llvm::OwningPtr<ASTUnit> Unit(
2074 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00002075 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00002076 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00002077 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00002078 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00002079 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00002080 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00002081 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00002082 CompleteTranslationUnit,
2083 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002084
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002085 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00002086 // Make sure to check that 'Unit' is non-NULL.
2087 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00002088 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2089 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002090 D != DEnd; ++D) {
2091 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00002092 CXString Msg = clang_formatDiagnostic(&Diag,
2093 clang_defaultDiagnosticDisplayOptions());
2094 fprintf(stderr, "%s\n", clang_getCString(Msg));
2095 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002096 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002097#ifdef LLVM_ON_WIN32
2098 // On Windows, force a flush, since there may be multiple copies of
2099 // stderr and stdout in the file system, all with different buffers
2100 // but writing to the same device.
2101 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00002102#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002103 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002104 }
Daniel Dunbar94220972009-12-05 02:17:18 +00002105
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002106 PTUI->result = Unit.take();
2107 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00002108 }
2109
Ted Kremenek139ba862009-10-22 00:03:57 +00002110 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002111 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002112
Ted Kremenek139ba862009-10-22 00:03:57 +00002113 // First add the complete path to the 'clang' executable.
2114 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002115 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002116
Ted Kremenek139ba862009-10-22 00:03:57 +00002117 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002118 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002119
Ted Kremenek139ba862009-10-22 00:03:57 +00002120 // The 'source_filename' argument is optional. If the caller does not
2121 // specify it then it is assumed that the source file is specified
2122 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002123 if (source_filename)
2124 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00002125
Steve Naroff37b5ac22009-10-15 20:50:09 +00002126 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00002127 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00002128 char astTmpFile[L_tmpnam];
2129 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002130
2131 // Since the Clang C library is primarily used by batch tools dealing with
2132 // (often very broken) source code, where spell-checking can have a
2133 // significant negative impact on performance (particularly when
2134 // precompiled headers are involved), we disable it by default.
2135 // Note that we place this argument early in the list, so that it can be
2136 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00002137 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00002138
Douglas Gregor4db64a42010-01-23 00:14:00 +00002139 // Remap any unsaved files to temporary files.
2140 std::vector<llvm::sys::Path> TemporaryFiles;
2141 std::vector<std::string> RemapArgs;
2142 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002143 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002144
Douglas Gregor4db64a42010-01-23 00:14:00 +00002145 // The pointers into the elements of RemapArgs are stable because we
2146 // won't be adding anything to RemapArgs after this point.
2147 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
2148 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002149
Ted Kremenek139ba862009-10-22 00:03:57 +00002150 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
2151 for (int i = 0; i < num_command_line_args; ++i)
2152 if (const char *arg = command_line_args[i]) {
2153 if (strcmp(arg, "-o") == 0) {
2154 ++i; // Also skip the matching argument.
2155 continue;
2156 }
2157 if (strcmp(arg, "-emit-ast") == 0 ||
2158 strcmp(arg, "-c") == 0 ||
2159 strcmp(arg, "-fsyntax-only") == 0) {
2160 continue;
2161 }
2162
2163 // Keep the argument.
2164 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002165 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002166
Douglas Gregord93256e2010-01-28 06:00:51 +00002167 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00002168 char tmpFileResults[L_tmpnam];
2169 char *tmpResultsFileName = tmpnam(tmpFileResults);
2170 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00002171 TemporaryFiles.push_back(DiagnosticsFile);
2172 argv.push_back("-fdiagnostics-binary");
2173
Douglas Gregor44c181a2010-07-23 00:33:23 +00002174 // Do we need the detailed preprocessing record?
2175 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2176 argv.push_back("-Xclang");
2177 argv.push_back("-detailed-preprocessing-record");
2178 }
2179
Ted Kremenek139ba862009-10-22 00:03:57 +00002180 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002181 argv.push_back(NULL);
2182
Ted Kremenekfeb15e32009-10-26 22:14:08 +00002183 // Invoke 'clang'.
2184 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
2185 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00002186 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00002187 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
2188 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00002189 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002190 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00002191 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002192
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002193 if (!ErrMsg.empty()) {
2194 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00002195 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002196 I != E; ++I) {
2197 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00002198 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002199 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00002200 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002201
Daniel Dunbar32141c82010-02-23 20:23:45 +00002202 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00002203 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00002204
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002205 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002206 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00002207 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00002208 RemappedFiles.size(),
2209 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00002210 if (ATU) {
2211 LoadSerializedDiagnostics(DiagnosticsFile,
2212 num_unsaved_files, unsaved_files,
2213 ATU->getFileManager(),
2214 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00002215 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002216 } else if (CXXIdx->getDisplayDiagnostics()) {
2217 // We failed to load the ASTUnit, but we can still deserialize the
2218 // diagnostics and emit them.
2219 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00002220 Diagnostic Diag;
2221 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002222 // FIXME: Faked LangOpts!
2223 LangOptions LangOpts;
2224 llvm::SmallVector<StoredDiagnostic, 4> Diags;
2225 LoadSerializedDiagnostics(DiagnosticsFile,
2226 num_unsaved_files, unsaved_files,
2227 FileMgr, SourceMgr, Diags);
2228 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
2229 DEnd = Diags.end();
2230 D != DEnd; ++D) {
2231 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00002232 CXString Msg = clang_formatDiagnostic(&Diag,
2233 clang_defaultDiagnosticDisplayOptions());
2234 fprintf(stderr, "%s\n", clang_getCString(Msg));
2235 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002236 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002237
2238#ifdef LLVM_ON_WIN32
2239 // On Windows, force a flush, since there may be multiple copies of
2240 // stderr and stdout in the file system, all with different buffers
2241 // but writing to the same device.
2242 fflush(stderr);
2243#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00002244 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002245
Douglas Gregor313e26c2010-02-18 23:35:40 +00002246 if (ATU) {
2247 // Make the translation unit responsible for destroying all temporary files.
2248 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2249 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002250 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00002251 } else {
2252 // Destroy all of the temporary files now; they can't be referenced any
2253 // longer.
2254 llvm::sys::Path(astTmpFile).eraseFromDisk();
2255 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2256 TemporaryFiles[i].eraseFromDisk();
2257 }
2258
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002259 PTUI->result = ATU;
2260}
2261CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2262 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002263 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002264 int num_command_line_args,
2265 struct CXUnsavedFile *unsaved_files,
2266 unsigned num_unsaved_files,
2267 unsigned options) {
2268 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2269 num_command_line_args, unsaved_files, num_unsaved_files,
2270 options, 0 };
2271 llvm::CrashRecoveryContext CRC;
2272
2273 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002274 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2275 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2276 fprintf(stderr, " 'command_line_args' : [");
2277 for (int i = 0; i != num_command_line_args; ++i) {
2278 if (i)
2279 fprintf(stderr, ", ");
2280 fprintf(stderr, "'%s'", command_line_args[i]);
2281 }
2282 fprintf(stderr, "],\n");
2283 fprintf(stderr, " 'unsaved_files' : [");
2284 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2285 if (i)
2286 fprintf(stderr, ", ");
2287 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2288 unsaved_files[i].Length);
2289 }
2290 fprintf(stderr, "],\n");
2291 fprintf(stderr, " 'options' : %d,\n", options);
2292 fprintf(stderr, "}\n");
2293
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002294 return 0;
2295 }
2296
2297 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002298}
2299
Douglas Gregor19998442010-08-13 15:35:05 +00002300unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2301 return CXSaveTranslationUnit_None;
2302}
2303
2304int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2305 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002306 if (!TU)
2307 return 1;
2308
2309 return static_cast<ASTUnit *>(TU)->Save(FileName);
2310}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002311
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002312void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002313 if (CTUnit) {
2314 // If the translation unit has been marked as unsafe to free, just discard
2315 // it.
2316 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2317 return;
2318
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002319 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002320 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002321}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002322
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002323unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2324 return CXReparse_None;
2325}
2326
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002327struct ReparseTranslationUnitInfo {
2328 CXTranslationUnit TU;
2329 unsigned num_unsaved_files;
2330 struct CXUnsavedFile *unsaved_files;
2331 unsigned options;
2332 int result;
2333};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002334
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002335static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002336 ReparseTranslationUnitInfo *RTUI =
2337 static_cast<ReparseTranslationUnitInfo*>(UserData);
2338 CXTranslationUnit TU = RTUI->TU;
2339 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2340 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2341 unsigned options = RTUI->options;
2342 (void) options;
2343 RTUI->result = 1;
2344
Douglas Gregorabc563f2010-07-19 21:46:24 +00002345 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002346 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002347
2348 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2349 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002350
2351 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2352 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2353 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2354 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002355 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002356 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2357 Buffer));
2358 }
2359
Douglas Gregor593b0c12010-09-23 18:47:53 +00002360 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2361 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002362}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002363
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002364int clang_reparseTranslationUnit(CXTranslationUnit TU,
2365 unsigned num_unsaved_files,
2366 struct CXUnsavedFile *unsaved_files,
2367 unsigned options) {
2368 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2369 options, 0 };
2370 llvm::CrashRecoveryContext CRC;
2371
2372 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002373 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002374 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2375 return 1;
2376 }
2377
2378 return RTUI.result;
2379}
2380
Douglas Gregordf95a132010-08-09 20:45:32 +00002381
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002382CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002383 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002384 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002385
Steve Naroff77accc12009-09-03 18:19:54 +00002386 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002387 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002388}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002389
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002390CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002391 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002392 return Result;
2393}
2394
Ted Kremenekfb480492010-01-13 21:46:36 +00002395} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002396
Ted Kremenekfb480492010-01-13 21:46:36 +00002397//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002398// CXSourceLocation and CXSourceRange Operations.
2399//===----------------------------------------------------------------------===//
2400
Douglas Gregorb9790342010-01-22 21:44:22 +00002401extern "C" {
2402CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002403 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002404 return Result;
2405}
2406
2407unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002408 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2409 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2410 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002411}
2412
2413CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2414 CXFile file,
2415 unsigned line,
2416 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002417 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002418 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002419
Douglas Gregorb9790342010-01-22 21:44:22 +00002420 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2421 SourceLocation SLoc
2422 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002423 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002424 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002425
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002426 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002427}
2428
Douglas Gregor5352ac02010-01-28 00:27:43 +00002429CXSourceRange clang_getNullRange() {
2430 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2431 return Result;
2432}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002433
Douglas Gregor5352ac02010-01-28 00:27:43 +00002434CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2435 if (begin.ptr_data[0] != end.ptr_data[0] ||
2436 begin.ptr_data[1] != end.ptr_data[1])
2437 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002438
2439 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002440 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002441 return Result;
2442}
2443
Douglas Gregor46766dc2010-01-26 19:19:08 +00002444void clang_getInstantiationLocation(CXSourceLocation location,
2445 CXFile *file,
2446 unsigned *line,
2447 unsigned *column,
2448 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002449 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2450
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002451 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002452 if (file)
2453 *file = 0;
2454 if (line)
2455 *line = 0;
2456 if (column)
2457 *column = 0;
2458 if (offset)
2459 *offset = 0;
2460 return;
2461 }
2462
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002463 const SourceManager &SM =
2464 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002465 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002466
2467 if (file)
2468 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2469 if (line)
2470 *line = SM.getInstantiationLineNumber(InstLoc);
2471 if (column)
2472 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002473 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002474 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002475}
2476
Douglas Gregor1db19de2010-01-19 21:36:55 +00002477CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002478 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002479 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002480 return Result;
2481}
2482
2483CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002484 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002485 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002486 return Result;
2487}
2488
Douglas Gregorb9790342010-01-22 21:44:22 +00002489} // end: extern "C"
2490
Douglas Gregor1db19de2010-01-19 21:36:55 +00002491//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002492// CXFile Operations.
2493//===----------------------------------------------------------------------===//
2494
2495extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002496CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002497 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002498 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002499
Steve Naroff88145032009-10-27 14:35:18 +00002500 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002501 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002502}
2503
2504time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002505 if (!SFile)
2506 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002507
Steve Naroff88145032009-10-27 14:35:18 +00002508 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2509 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002510}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002511
Douglas Gregorb9790342010-01-22 21:44:22 +00002512CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2513 if (!tu)
2514 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002515
Douglas Gregorb9790342010-01-22 21:44:22 +00002516 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002517
Douglas Gregorb9790342010-01-22 21:44:22 +00002518 FileManager &FMgr = CXXUnit->getFileManager();
2519 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2520 return const_cast<FileEntry *>(File);
2521}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002522
Ted Kremenekfb480492010-01-13 21:46:36 +00002523} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002524
Ted Kremenekfb480492010-01-13 21:46:36 +00002525//===----------------------------------------------------------------------===//
2526// CXCursor Operations.
2527//===----------------------------------------------------------------------===//
2528
Ted Kremenekfb480492010-01-13 21:46:36 +00002529static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002530 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2531 return getDeclFromExpr(CE->getSubExpr());
2532
Ted Kremenekfb480492010-01-13 21:46:36 +00002533 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2534 return RefExpr->getDecl();
2535 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2536 return ME->getMemberDecl();
2537 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2538 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002539 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2540 return PRE->getProperty();
2541
Ted Kremenekfb480492010-01-13 21:46:36 +00002542 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2543 return getDeclFromExpr(CE->getCallee());
Ted Kremenekfb480492010-01-13 21:46:36 +00002544 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2545 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002546
Douglas Gregordb1314e2010-10-01 21:11:22 +00002547 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2548 return PE->getProtocol();
2549
Ted Kremenekfb480492010-01-13 21:46:36 +00002550 return 0;
2551}
2552
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002553static SourceLocation getLocationFromExpr(Expr *E) {
2554 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2555 return /*FIXME:*/Msg->getLeftLoc();
2556 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2557 return DRE->getLocation();
2558 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2559 return Member->getMemberLoc();
2560 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2561 return Ivar->getLocation();
2562 return E->getLocStart();
2563}
2564
Ted Kremenekfb480492010-01-13 21:46:36 +00002565extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002566
2567unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002568 CXCursorVisitor visitor,
2569 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002570 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002571
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002572 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2573 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002574 return CursorVis.VisitChildren(parent);
2575}
2576
Douglas Gregor78205d42010-01-20 21:45:58 +00002577static CXString getDeclSpelling(Decl *D) {
2578 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2579 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002580 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002581
Douglas Gregor78205d42010-01-20 21:45:58 +00002582 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002583 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002584
Douglas Gregor78205d42010-01-20 21:45:58 +00002585 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2586 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2587 // and returns different names. NamedDecl returns the class name and
2588 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002589 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002590
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002591 if (isa<UsingDirectiveDecl>(D))
2592 return createCXString("");
2593
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002594 llvm::SmallString<1024> S;
2595 llvm::raw_svector_ostream os(S);
2596 ND->printName(os);
2597
2598 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002599}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002600
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002601CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002602 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002603 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002604
Steve Narofff334b4e2009-09-02 18:26:48 +00002605 if (clang_isReference(C.kind)) {
2606 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002607 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002608 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002609 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002610 }
2611 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002612 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002613 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002614 }
2615 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002616 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002617 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002618 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002619 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002620 case CXCursor_CXXBaseSpecifier: {
2621 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2622 return createCXString(B->getType().getAsString());
2623 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002624 case CXCursor_TypeRef: {
2625 TypeDecl *Type = getCursorTypeRef(C).first;
2626 assert(Type && "Missing type decl");
2627
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002628 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2629 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002630 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002631 case CXCursor_TemplateRef: {
2632 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002633 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002634
2635 return createCXString(Template->getNameAsString());
2636 }
Douglas Gregor69319002010-08-31 23:48:11 +00002637
2638 case CXCursor_NamespaceRef: {
2639 NamedDecl *NS = getCursorNamespaceRef(C).first;
2640 assert(NS && "Missing namespace decl");
2641
2642 return createCXString(NS->getNameAsString());
2643 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002644
Douglas Gregora67e03f2010-09-09 21:42:20 +00002645 case CXCursor_MemberRef: {
2646 FieldDecl *Field = getCursorMemberRef(C).first;
2647 assert(Field && "Missing member decl");
2648
2649 return createCXString(Field->getNameAsString());
2650 }
2651
Douglas Gregor36897b02010-09-10 00:22:18 +00002652 case CXCursor_LabelRef: {
2653 LabelStmt *Label = getCursorLabelRef(C).first;
2654 assert(Label && "Missing label");
2655
2656 return createCXString(Label->getID()->getName());
2657 }
2658
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002659 case CXCursor_OverloadedDeclRef: {
2660 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2661 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2662 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2663 return createCXString(ND->getNameAsString());
2664 return createCXString("");
2665 }
2666 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2667 return createCXString(E->getName().getAsString());
2668 OverloadedTemplateStorage *Ovl
2669 = Storage.get<OverloadedTemplateStorage*>();
2670 if (Ovl->size() == 0)
2671 return createCXString("");
2672 return createCXString((*Ovl->begin())->getNameAsString());
2673 }
2674
Daniel Dunbaracca7252009-11-30 20:42:49 +00002675 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002676 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002677 }
2678 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002679
2680 if (clang_isExpression(C.kind)) {
2681 Decl *D = getDeclFromExpr(getCursorExpr(C));
2682 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002683 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002684 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002685 }
2686
Douglas Gregor36897b02010-09-10 00:22:18 +00002687 if (clang_isStatement(C.kind)) {
2688 Stmt *S = getCursorStmt(C);
2689 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2690 return createCXString(Label->getID()->getName());
2691
2692 return createCXString("");
2693 }
2694
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002695 if (C.kind == CXCursor_MacroInstantiation)
2696 return createCXString(getCursorMacroInstantiation(C)->getName()
2697 ->getNameStart());
2698
Douglas Gregor572feb22010-03-18 18:04:21 +00002699 if (C.kind == CXCursor_MacroDefinition)
2700 return createCXString(getCursorMacroDefinition(C)->getName()
2701 ->getNameStart());
2702
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002703 if (clang_isDeclaration(C.kind))
2704 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002705
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002706 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002707}
2708
Douglas Gregor358559d2010-10-02 22:49:11 +00002709CXString clang_getCursorDisplayName(CXCursor C) {
2710 if (!clang_isDeclaration(C.kind))
2711 return clang_getCursorSpelling(C);
2712
2713 Decl *D = getCursorDecl(C);
2714 if (!D)
2715 return createCXString("");
2716
2717 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2718 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2719 D = FunTmpl->getTemplatedDecl();
2720
2721 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2722 llvm::SmallString<64> Str;
2723 llvm::raw_svector_ostream OS(Str);
2724 OS << Function->getNameAsString();
2725 if (Function->getPrimaryTemplate())
2726 OS << "<>";
2727 OS << "(";
2728 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2729 if (I)
2730 OS << ", ";
2731 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2732 }
2733
2734 if (Function->isVariadic()) {
2735 if (Function->getNumParams())
2736 OS << ", ";
2737 OS << "...";
2738 }
2739 OS << ")";
2740 return createCXString(OS.str());
2741 }
2742
2743 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2744 llvm::SmallString<64> Str;
2745 llvm::raw_svector_ostream OS(Str);
2746 OS << ClassTemplate->getNameAsString();
2747 OS << "<";
2748 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2749 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2750 if (I)
2751 OS << ", ";
2752
2753 NamedDecl *Param = Params->getParam(I);
2754 if (Param->getIdentifier()) {
2755 OS << Param->getIdentifier()->getName();
2756 continue;
2757 }
2758
2759 // There is no parameter name, which makes this tricky. Try to come up
2760 // with something useful that isn't too long.
2761 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2762 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2763 else if (NonTypeTemplateParmDecl *NTTP
2764 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2765 OS << NTTP->getType().getAsString(Policy);
2766 else
2767 OS << "template<...> class";
2768 }
2769
2770 OS << ">";
2771 return createCXString(OS.str());
2772 }
2773
2774 if (ClassTemplateSpecializationDecl *ClassSpec
2775 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2776 // If the type was explicitly written, use that.
2777 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2778 return createCXString(TSInfo->getType().getAsString(Policy));
2779
2780 llvm::SmallString<64> Str;
2781 llvm::raw_svector_ostream OS(Str);
2782 OS << ClassSpec->getNameAsString();
2783 OS << TemplateSpecializationType::PrintTemplateArgumentList(
2784 ClassSpec->getTemplateArgs().getFlatArgumentList(),
2785 ClassSpec->getTemplateArgs().flat_size(),
2786 Policy);
2787 return createCXString(OS.str());
2788 }
2789
2790 return clang_getCursorSpelling(C);
2791}
2792
Ted Kremeneke68fff62010-02-17 00:41:32 +00002793CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002794 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002795 case CXCursor_FunctionDecl:
2796 return createCXString("FunctionDecl");
2797 case CXCursor_TypedefDecl:
2798 return createCXString("TypedefDecl");
2799 case CXCursor_EnumDecl:
2800 return createCXString("EnumDecl");
2801 case CXCursor_EnumConstantDecl:
2802 return createCXString("EnumConstantDecl");
2803 case CXCursor_StructDecl:
2804 return createCXString("StructDecl");
2805 case CXCursor_UnionDecl:
2806 return createCXString("UnionDecl");
2807 case CXCursor_ClassDecl:
2808 return createCXString("ClassDecl");
2809 case CXCursor_FieldDecl:
2810 return createCXString("FieldDecl");
2811 case CXCursor_VarDecl:
2812 return createCXString("VarDecl");
2813 case CXCursor_ParmDecl:
2814 return createCXString("ParmDecl");
2815 case CXCursor_ObjCInterfaceDecl:
2816 return createCXString("ObjCInterfaceDecl");
2817 case CXCursor_ObjCCategoryDecl:
2818 return createCXString("ObjCCategoryDecl");
2819 case CXCursor_ObjCProtocolDecl:
2820 return createCXString("ObjCProtocolDecl");
2821 case CXCursor_ObjCPropertyDecl:
2822 return createCXString("ObjCPropertyDecl");
2823 case CXCursor_ObjCIvarDecl:
2824 return createCXString("ObjCIvarDecl");
2825 case CXCursor_ObjCInstanceMethodDecl:
2826 return createCXString("ObjCInstanceMethodDecl");
2827 case CXCursor_ObjCClassMethodDecl:
2828 return createCXString("ObjCClassMethodDecl");
2829 case CXCursor_ObjCImplementationDecl:
2830 return createCXString("ObjCImplementationDecl");
2831 case CXCursor_ObjCCategoryImplDecl:
2832 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002833 case CXCursor_CXXMethod:
2834 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002835 case CXCursor_UnexposedDecl:
2836 return createCXString("UnexposedDecl");
2837 case CXCursor_ObjCSuperClassRef:
2838 return createCXString("ObjCSuperClassRef");
2839 case CXCursor_ObjCProtocolRef:
2840 return createCXString("ObjCProtocolRef");
2841 case CXCursor_ObjCClassRef:
2842 return createCXString("ObjCClassRef");
2843 case CXCursor_TypeRef:
2844 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002845 case CXCursor_TemplateRef:
2846 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002847 case CXCursor_NamespaceRef:
2848 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002849 case CXCursor_MemberRef:
2850 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002851 case CXCursor_LabelRef:
2852 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002853 case CXCursor_OverloadedDeclRef:
2854 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002855 case CXCursor_UnexposedExpr:
2856 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002857 case CXCursor_BlockExpr:
2858 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002859 case CXCursor_DeclRefExpr:
2860 return createCXString("DeclRefExpr");
2861 case CXCursor_MemberRefExpr:
2862 return createCXString("MemberRefExpr");
2863 case CXCursor_CallExpr:
2864 return createCXString("CallExpr");
2865 case CXCursor_ObjCMessageExpr:
2866 return createCXString("ObjCMessageExpr");
2867 case CXCursor_UnexposedStmt:
2868 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002869 case CXCursor_LabelStmt:
2870 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002871 case CXCursor_InvalidFile:
2872 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002873 case CXCursor_InvalidCode:
2874 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002875 case CXCursor_NoDeclFound:
2876 return createCXString("NoDeclFound");
2877 case CXCursor_NotImplemented:
2878 return createCXString("NotImplemented");
2879 case CXCursor_TranslationUnit:
2880 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002881 case CXCursor_UnexposedAttr:
2882 return createCXString("UnexposedAttr");
2883 case CXCursor_IBActionAttr:
2884 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002885 case CXCursor_IBOutletAttr:
2886 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002887 case CXCursor_IBOutletCollectionAttr:
2888 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002889 case CXCursor_PreprocessingDirective:
2890 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002891 case CXCursor_MacroDefinition:
2892 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002893 case CXCursor_MacroInstantiation:
2894 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002895 case CXCursor_Namespace:
2896 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002897 case CXCursor_LinkageSpec:
2898 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002899 case CXCursor_CXXBaseSpecifier:
2900 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002901 case CXCursor_Constructor:
2902 return createCXString("CXXConstructor");
2903 case CXCursor_Destructor:
2904 return createCXString("CXXDestructor");
2905 case CXCursor_ConversionFunction:
2906 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002907 case CXCursor_TemplateTypeParameter:
2908 return createCXString("TemplateTypeParameter");
2909 case CXCursor_NonTypeTemplateParameter:
2910 return createCXString("NonTypeTemplateParameter");
2911 case CXCursor_TemplateTemplateParameter:
2912 return createCXString("TemplateTemplateParameter");
2913 case CXCursor_FunctionTemplate:
2914 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002915 case CXCursor_ClassTemplate:
2916 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002917 case CXCursor_ClassTemplatePartialSpecialization:
2918 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002919 case CXCursor_NamespaceAlias:
2920 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002921 case CXCursor_UsingDirective:
2922 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002923 case CXCursor_UsingDeclaration:
2924 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002925 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002926
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002927 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002928 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002929}
Steve Naroff89922f82009-08-31 00:59:03 +00002930
Ted Kremeneke68fff62010-02-17 00:41:32 +00002931enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2932 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002933 CXClientData client_data) {
2934 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2935 *BestCursor = cursor;
2936 return CXChildVisit_Recurse;
2937}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002938
Douglas Gregorb9790342010-01-22 21:44:22 +00002939CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2940 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002941 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002942
Douglas Gregorb9790342010-01-22 21:44:22 +00002943 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002944 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2945
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002946 // Translate the given source location to make it point at the beginning of
2947 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002948 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002949
2950 // Guard against an invalid SourceLocation, or we may assert in one
2951 // of the following calls.
2952 if (SLoc.isInvalid())
2953 return clang_getNullCursor();
2954
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002955 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2956 CXXUnit->getASTContext().getLangOptions());
2957
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002958 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2959 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002960 // FIXME: Would be great to have a "hint" cursor, then walk from that
2961 // hint cursor upward until we find a cursor whose source range encloses
2962 // the region of interest, rather than starting from the translation unit.
2963 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002964 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002965 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002966 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002967 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002968 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002969}
2970
Ted Kremenek73885552009-11-17 19:28:59 +00002971CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002972 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002973}
2974
2975unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002976 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002977}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002978
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002979unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002980 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2981}
2982
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002983unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002984 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2985}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002986
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002987unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002988 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2989}
2990
Douglas Gregor97b98722010-01-19 23:20:36 +00002991unsigned clang_isExpression(enum CXCursorKind K) {
2992 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2993}
2994
2995unsigned clang_isStatement(enum CXCursorKind K) {
2996 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2997}
2998
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002999unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3000 return K == CXCursor_TranslationUnit;
3001}
3002
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003003unsigned clang_isPreprocessing(enum CXCursorKind K) {
3004 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3005}
3006
Ted Kremenekad6eff62010-03-08 21:17:29 +00003007unsigned clang_isUnexposed(enum CXCursorKind K) {
3008 switch (K) {
3009 case CXCursor_UnexposedDecl:
3010 case CXCursor_UnexposedExpr:
3011 case CXCursor_UnexposedStmt:
3012 case CXCursor_UnexposedAttr:
3013 return true;
3014 default:
3015 return false;
3016 }
3017}
3018
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003019CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003020 return C.kind;
3021}
3022
Douglas Gregor98258af2010-01-18 22:46:11 +00003023CXSourceLocation clang_getCursorLocation(CXCursor C) {
3024 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003025 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003026 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003027 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3028 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003029 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003030 }
3031
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003032 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003033 std::pair<ObjCProtocolDecl *, SourceLocation> P
3034 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003035 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003036 }
3037
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003038 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003039 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3040 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003041 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003042 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003043
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003044 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003045 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003046 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003047 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003048
3049 case CXCursor_TemplateRef: {
3050 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3051 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3052 }
3053
Douglas Gregor69319002010-08-31 23:48:11 +00003054 case CXCursor_NamespaceRef: {
3055 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3056 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3057 }
3058
Douglas Gregora67e03f2010-09-09 21:42:20 +00003059 case CXCursor_MemberRef: {
3060 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3061 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3062 }
3063
Ted Kremenek3064ef92010-08-27 21:34:58 +00003064 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003065 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3066 if (!BaseSpec)
3067 return clang_getNullLocation();
3068
3069 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3070 return cxloc::translateSourceLocation(getCursorContext(C),
3071 TSInfo->getTypeLoc().getBeginLoc());
3072
3073 return cxloc::translateSourceLocation(getCursorContext(C),
3074 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003075 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003076
Douglas Gregor36897b02010-09-10 00:22:18 +00003077 case CXCursor_LabelRef: {
3078 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3079 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3080 }
3081
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003082 case CXCursor_OverloadedDeclRef:
3083 return cxloc::translateSourceLocation(getCursorContext(C),
3084 getCursorOverloadedDeclRef(C).second);
3085
Douglas Gregorf46034a2010-01-18 23:41:10 +00003086 default:
3087 // FIXME: Need a way to enumerate all non-reference cases.
3088 llvm_unreachable("Missed a reference kind");
3089 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003090 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003091
3092 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003093 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003094 getLocationFromExpr(getCursorExpr(C)));
3095
Douglas Gregor36897b02010-09-10 00:22:18 +00003096 if (clang_isStatement(C.kind))
3097 return cxloc::translateSourceLocation(getCursorContext(C),
3098 getCursorStmt(C)->getLocStart());
3099
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003100 if (C.kind == CXCursor_PreprocessingDirective) {
3101 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3102 return cxloc::translateSourceLocation(getCursorContext(C), L);
3103 }
Douglas Gregor48072312010-03-18 15:23:44 +00003104
3105 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003106 SourceLocation L
3107 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003108 return cxloc::translateSourceLocation(getCursorContext(C), L);
3109 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003110
3111 if (C.kind == CXCursor_MacroDefinition) {
3112 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3113 return cxloc::translateSourceLocation(getCursorContext(C), L);
3114 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003115
Ted Kremenek9a700d22010-05-12 06:16:13 +00003116 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003117 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003118
Douglas Gregorf46034a2010-01-18 23:41:10 +00003119 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003120 SourceLocation Loc = D->getLocation();
3121 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3122 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003123 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003124}
Douglas Gregora7bde202010-01-19 00:34:46 +00003125
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003126} // end extern "C"
3127
3128static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003129 if (clang_isReference(C.kind)) {
3130 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003131 case CXCursor_ObjCSuperClassRef:
3132 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003133
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003134 case CXCursor_ObjCProtocolRef:
3135 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003136
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003137 case CXCursor_ObjCClassRef:
3138 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003139
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003140 case CXCursor_TypeRef:
3141 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003142
3143 case CXCursor_TemplateRef:
3144 return getCursorTemplateRef(C).second;
3145
Douglas Gregor69319002010-08-31 23:48:11 +00003146 case CXCursor_NamespaceRef:
3147 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003148
3149 case CXCursor_MemberRef:
3150 return getCursorMemberRef(C).second;
3151
Ted Kremenek3064ef92010-08-27 21:34:58 +00003152 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003153 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003154
Douglas Gregor36897b02010-09-10 00:22:18 +00003155 case CXCursor_LabelRef:
3156 return getCursorLabelRef(C).second;
3157
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003158 case CXCursor_OverloadedDeclRef:
3159 return getCursorOverloadedDeclRef(C).second;
3160
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003161 default:
3162 // FIXME: Need a way to enumerate all non-reference cases.
3163 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003164 }
3165 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003166
3167 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003168 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003169
3170 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003171 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003172
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003173 if (C.kind == CXCursor_PreprocessingDirective)
3174 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003175
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003176 if (C.kind == CXCursor_MacroInstantiation)
3177 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003178
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003179 if (C.kind == CXCursor_MacroDefinition)
3180 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003181
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003182 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
3183 return getCursorDecl(C)->getSourceRange();
3184
3185 return SourceRange();
3186}
3187
3188extern "C" {
3189
3190CXSourceRange clang_getCursorExtent(CXCursor C) {
3191 SourceRange R = getRawCursorExtent(C);
3192 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003193 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003194
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003195 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003196}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003197
3198CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003199 if (clang_isInvalid(C.kind))
3200 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003201
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003202 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003203 if (clang_isDeclaration(C.kind)) {
3204 Decl *D = getCursorDecl(C);
3205 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3206 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3207 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3208 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3209 if (ObjCForwardProtocolDecl *Protocols
3210 = dyn_cast<ObjCForwardProtocolDecl>(D))
3211 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3212
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003213 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003214 }
3215
Douglas Gregor97b98722010-01-19 23:20:36 +00003216 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003217 Expr *E = getCursorExpr(C);
3218 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003219 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003220 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003221
3222 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3223 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3224
Douglas Gregor97b98722010-01-19 23:20:36 +00003225 return clang_getNullCursor();
3226 }
3227
Douglas Gregor36897b02010-09-10 00:22:18 +00003228 if (clang_isStatement(C.kind)) {
3229 Stmt *S = getCursorStmt(C);
3230 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3231 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3232 getCursorASTUnit(C));
3233
3234 return clang_getNullCursor();
3235 }
3236
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003237 if (C.kind == CXCursor_MacroInstantiation) {
3238 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3239 return MakeMacroDefinitionCursor(Def, CXXUnit);
3240 }
3241
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003242 if (!clang_isReference(C.kind))
3243 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003244
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003245 switch (C.kind) {
3246 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003247 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003248
3249 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003250 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003251
3252 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003253 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003254
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003255 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003256 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003257
3258 case CXCursor_TemplateRef:
3259 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3260
Douglas Gregor69319002010-08-31 23:48:11 +00003261 case CXCursor_NamespaceRef:
3262 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3263
Douglas Gregora67e03f2010-09-09 21:42:20 +00003264 case CXCursor_MemberRef:
3265 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3266
Ted Kremenek3064ef92010-08-27 21:34:58 +00003267 case CXCursor_CXXBaseSpecifier: {
3268 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3269 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3270 CXXUnit));
3271 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003272
Douglas Gregor36897b02010-09-10 00:22:18 +00003273 case CXCursor_LabelRef:
3274 // FIXME: We end up faking the "parent" declaration here because we
3275 // don't want to make CXCursor larger.
3276 return MakeCXCursor(getCursorLabelRef(C).first,
3277 CXXUnit->getASTContext().getTranslationUnitDecl(),
3278 CXXUnit);
3279
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003280 case CXCursor_OverloadedDeclRef:
3281 return C;
3282
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003283 default:
3284 // We would prefer to enumerate all non-reference cursor kinds here.
3285 llvm_unreachable("Unhandled reference cursor kind");
3286 break;
3287 }
3288 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003289
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003290 return clang_getNullCursor();
3291}
3292
Douglas Gregorb6998662010-01-19 19:34:47 +00003293CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003294 if (clang_isInvalid(C.kind))
3295 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003296
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003297 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003298
Douglas Gregorb6998662010-01-19 19:34:47 +00003299 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003300 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003301 C = clang_getCursorReferenced(C);
3302 WasReference = true;
3303 }
3304
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003305 if (C.kind == CXCursor_MacroInstantiation)
3306 return clang_getCursorReferenced(C);
3307
Douglas Gregorb6998662010-01-19 19:34:47 +00003308 if (!clang_isDeclaration(C.kind))
3309 return clang_getNullCursor();
3310
3311 Decl *D = getCursorDecl(C);
3312 if (!D)
3313 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003314
Douglas Gregorb6998662010-01-19 19:34:47 +00003315 switch (D->getKind()) {
3316 // Declaration kinds that don't really separate the notions of
3317 // declaration and definition.
3318 case Decl::Namespace:
3319 case Decl::Typedef:
3320 case Decl::TemplateTypeParm:
3321 case Decl::EnumConstant:
3322 case Decl::Field:
3323 case Decl::ObjCIvar:
3324 case Decl::ObjCAtDefsField:
3325 case Decl::ImplicitParam:
3326 case Decl::ParmVar:
3327 case Decl::NonTypeTemplateParm:
3328 case Decl::TemplateTemplateParm:
3329 case Decl::ObjCCategoryImpl:
3330 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003331 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003332 case Decl::LinkageSpec:
3333 case Decl::ObjCPropertyImpl:
3334 case Decl::FileScopeAsm:
3335 case Decl::StaticAssert:
3336 case Decl::Block:
3337 return C;
3338
3339 // Declaration kinds that don't make any sense here, but are
3340 // nonetheless harmless.
3341 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003342 break;
3343
3344 // Declaration kinds for which the definition is not resolvable.
3345 case Decl::UnresolvedUsingTypename:
3346 case Decl::UnresolvedUsingValue:
3347 break;
3348
3349 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003350 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3351 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003352
3353 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003354 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003355
3356 case Decl::Enum:
3357 case Decl::Record:
3358 case Decl::CXXRecord:
3359 case Decl::ClassTemplateSpecialization:
3360 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003361 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003362 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003363 return clang_getNullCursor();
3364
3365 case Decl::Function:
3366 case Decl::CXXMethod:
3367 case Decl::CXXConstructor:
3368 case Decl::CXXDestructor:
3369 case Decl::CXXConversion: {
3370 const FunctionDecl *Def = 0;
3371 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003372 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003373 return clang_getNullCursor();
3374 }
3375
3376 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003377 // Ask the variable if it has a definition.
3378 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3379 return MakeCXCursor(Def, CXXUnit);
3380 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003381 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003382
Douglas Gregorb6998662010-01-19 19:34:47 +00003383 case Decl::FunctionTemplate: {
3384 const FunctionDecl *Def = 0;
3385 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003386 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003387 return clang_getNullCursor();
3388 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003389
Douglas Gregorb6998662010-01-19 19:34:47 +00003390 case Decl::ClassTemplate: {
3391 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003392 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003393 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003394 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003395 return clang_getNullCursor();
3396 }
3397
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003398 case Decl::Using:
3399 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3400 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003401
3402 case Decl::UsingShadow:
3403 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003404 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003405 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003406
3407 case Decl::ObjCMethod: {
3408 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3409 if (Method->isThisDeclarationADefinition())
3410 return C;
3411
3412 // Dig out the method definition in the associated
3413 // @implementation, if we have it.
3414 // FIXME: The ASTs should make finding the definition easier.
3415 if (ObjCInterfaceDecl *Class
3416 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3417 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3418 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3419 Method->isInstanceMethod()))
3420 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003421 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003422
3423 return clang_getNullCursor();
3424 }
3425
3426 case Decl::ObjCCategory:
3427 if (ObjCCategoryImplDecl *Impl
3428 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003429 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003430 return clang_getNullCursor();
3431
3432 case Decl::ObjCProtocol:
3433 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3434 return C;
3435 return clang_getNullCursor();
3436
3437 case Decl::ObjCInterface:
3438 // There are two notions of a "definition" for an Objective-C
3439 // class: the interface and its implementation. When we resolved a
3440 // reference to an Objective-C class, produce the @interface as
3441 // the definition; when we were provided with the interface,
3442 // produce the @implementation as the definition.
3443 if (WasReference) {
3444 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3445 return C;
3446 } else if (ObjCImplementationDecl *Impl
3447 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003448 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003449 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003450
Douglas Gregorb6998662010-01-19 19:34:47 +00003451 case Decl::ObjCProperty:
3452 // FIXME: We don't really know where to find the
3453 // ObjCPropertyImplDecls that implement this property.
3454 return clang_getNullCursor();
3455
3456 case Decl::ObjCCompatibleAlias:
3457 if (ObjCInterfaceDecl *Class
3458 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3459 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003460 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003461
Douglas Gregorb6998662010-01-19 19:34:47 +00003462 return clang_getNullCursor();
3463
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003464 case Decl::ObjCForwardProtocol:
3465 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3466 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003467
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003468 case Decl::ObjCClass:
3469 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3470 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003471
3472 case Decl::Friend:
3473 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003474 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003475 return clang_getNullCursor();
3476
3477 case Decl::FriendTemplate:
3478 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003479 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003480 return clang_getNullCursor();
3481 }
3482
3483 return clang_getNullCursor();
3484}
3485
3486unsigned clang_isCursorDefinition(CXCursor C) {
3487 if (!clang_isDeclaration(C.kind))
3488 return 0;
3489
3490 return clang_getCursorDefinition(C) == C;
3491}
3492
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003493unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003494 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003495 return 0;
3496
3497 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3498 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3499 return E->getNumDecls();
3500
3501 if (OverloadedTemplateStorage *S
3502 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3503 return S->size();
3504
3505 Decl *D = Storage.get<Decl*>();
3506 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3507 return Using->getNumShadowDecls();
3508 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3509 return Classes->size();
3510 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3511 return Protocols->protocol_size();
3512
3513 return 0;
3514}
3515
3516CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003517 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003518 return clang_getNullCursor();
3519
3520 if (index >= clang_getNumOverloadedDecls(cursor))
3521 return clang_getNullCursor();
3522
3523 ASTUnit *Unit = getCursorASTUnit(cursor);
3524 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3525 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3526 return MakeCXCursor(E->decls_begin()[index], Unit);
3527
3528 if (OverloadedTemplateStorage *S
3529 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3530 return MakeCXCursor(S->begin()[index], Unit);
3531
3532 Decl *D = Storage.get<Decl*>();
3533 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3534 // FIXME: This is, unfortunately, linear time.
3535 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3536 std::advance(Pos, index);
3537 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3538 }
3539
3540 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3541 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3542
3543 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3544 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3545
3546 return clang_getNullCursor();
3547}
3548
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003549void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003550 const char **startBuf,
3551 const char **endBuf,
3552 unsigned *startLine,
3553 unsigned *startColumn,
3554 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003555 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003556 assert(getCursorDecl(C) && "CXCursor has null decl");
3557 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003558 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3559 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003560
Steve Naroff4ade6d62009-09-23 17:52:52 +00003561 SourceManager &SM = FD->getASTContext().getSourceManager();
3562 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3563 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3564 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3565 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3566 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3567 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3568}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003569
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003570void clang_enableStackTraces(void) {
3571 llvm::sys::PrintStackTraceOnErrorSignal();
3572}
3573
Ted Kremenekfb480492010-01-13 21:46:36 +00003574} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003575
Ted Kremenekfb480492010-01-13 21:46:36 +00003576//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003577// Token-based Operations.
3578//===----------------------------------------------------------------------===//
3579
3580/* CXToken layout:
3581 * int_data[0]: a CXTokenKind
3582 * int_data[1]: starting token location
3583 * int_data[2]: token length
3584 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003585 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003586 * otherwise unused.
3587 */
3588extern "C" {
3589
3590CXTokenKind clang_getTokenKind(CXToken CXTok) {
3591 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3592}
3593
3594CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3595 switch (clang_getTokenKind(CXTok)) {
3596 case CXToken_Identifier:
3597 case CXToken_Keyword:
3598 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003599 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3600 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003601
3602 case CXToken_Literal: {
3603 // We have stashed the starting pointer in the ptr_data field. Use it.
3604 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003605 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003606 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003607
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003608 case CXToken_Punctuation:
3609 case CXToken_Comment:
3610 break;
3611 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003612
3613 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003614 // deconstructing the source location.
3615 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3616 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003617 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003618
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003619 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3620 std::pair<FileID, unsigned> LocInfo
3621 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003622 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003623 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003624 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3625 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003626 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003627
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003628 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003629}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003630
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003631CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3632 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3633 if (!CXXUnit)
3634 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003635
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003636 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3637 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3638}
3639
3640CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3641 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003642 if (!CXXUnit)
3643 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003644
3645 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003646 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3647}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003648
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003649void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3650 CXToken **Tokens, unsigned *NumTokens) {
3651 if (Tokens)
3652 *Tokens = 0;
3653 if (NumTokens)
3654 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003655
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003656 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3657 if (!CXXUnit || !Tokens || !NumTokens)
3658 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003659
Douglas Gregorbdf60622010-03-05 21:16:25 +00003660 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3661
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003662 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003663 if (R.isInvalid())
3664 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003665
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003666 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3667 std::pair<FileID, unsigned> BeginLocInfo
3668 = SourceMgr.getDecomposedLoc(R.getBegin());
3669 std::pair<FileID, unsigned> EndLocInfo
3670 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003671
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003672 // Cannot tokenize across files.
3673 if (BeginLocInfo.first != EndLocInfo.first)
3674 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003675
3676 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003677 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003678 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003679 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003680 if (Invalid)
3681 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003682
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003683 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3684 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003685 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003686 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003687
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003688 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003689 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003690 llvm::SmallVector<CXToken, 32> CXTokens;
3691 Token Tok;
3692 do {
3693 // Lex the next token
3694 Lex.LexFromRawLexer(Tok);
3695 if (Tok.is(tok::eof))
3696 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003697
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003698 // Initialize the CXToken.
3699 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003700
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003701 // - Common fields
3702 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3703 CXTok.int_data[2] = Tok.getLength();
3704 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003705
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003706 // - Kind-specific fields
3707 if (Tok.isLiteral()) {
3708 CXTok.int_data[0] = CXToken_Literal;
3709 CXTok.ptr_data = (void *)Tok.getLiteralData();
3710 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003711 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003712 std::pair<FileID, unsigned> LocInfo
3713 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003714 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003715 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003716 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3717 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003718 return;
3719
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003720 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003721 IdentifierInfo *II
3722 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003723
3724 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3725 CXTok.int_data[0] = CXToken_Keyword;
3726 }
3727 else {
3728 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3729 CXToken_Identifier
3730 : CXToken_Keyword;
3731 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003732 CXTok.ptr_data = II;
3733 } else if (Tok.is(tok::comment)) {
3734 CXTok.int_data[0] = CXToken_Comment;
3735 CXTok.ptr_data = 0;
3736 } else {
3737 CXTok.int_data[0] = CXToken_Punctuation;
3738 CXTok.ptr_data = 0;
3739 }
3740 CXTokens.push_back(CXTok);
3741 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003742
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003743 if (CXTokens.empty())
3744 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003745
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003746 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3747 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3748 *NumTokens = CXTokens.size();
3749}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003750
Ted Kremenek6db61092010-05-05 00:55:15 +00003751void clang_disposeTokens(CXTranslationUnit TU,
3752 CXToken *Tokens, unsigned NumTokens) {
3753 free(Tokens);
3754}
3755
3756} // end: extern "C"
3757
3758//===----------------------------------------------------------------------===//
3759// Token annotation APIs.
3760//===----------------------------------------------------------------------===//
3761
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003762typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003763static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3764 CXCursor parent,
3765 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003766namespace {
3767class AnnotateTokensWorker {
3768 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003769 CXToken *Tokens;
3770 CXCursor *Cursors;
3771 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003772 unsigned TokIdx;
3773 CursorVisitor AnnotateVis;
3774 SourceManager &SrcMgr;
3775
3776 bool MoreTokens() const { return TokIdx < NumTokens; }
3777 unsigned NextToken() const { return TokIdx; }
3778 void AdvanceToken() { ++TokIdx; }
3779 SourceLocation GetTokenLoc(unsigned tokI) {
3780 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3781 }
3782
Ted Kremenek6db61092010-05-05 00:55:15 +00003783public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003784 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003785 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3786 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003787 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003788 NumTokens(numTokens), TokIdx(0),
3789 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3790 Decl::MaxPCHLevel, RegionOfInterest),
3791 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003792
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003793 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003794 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003795 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003796};
3797}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003798
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003799void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3800 // Walk the AST within the region of interest, annotating tokens
3801 // along the way.
3802 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003803
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003804 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3805 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3806 if (Pos != Annotated.end())
3807 Cursors[I] = Pos->second;
3808 }
3809
3810 // Finish up annotating any tokens left.
3811 if (!MoreTokens())
3812 return;
3813
3814 const CXCursor &C = clang_getNullCursor();
3815 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3816 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3817 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003818 }
3819}
3820
Ted Kremenek6db61092010-05-05 00:55:15 +00003821enum CXChildVisitResult
3822AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003823 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3824 // We can always annotate a preprocessing directive/macro instantiation.
3825 if (clang_isPreprocessing(cursor.kind)) {
3826 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003827 return CXChildVisit_Recurse;
3828 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003829
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003830 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003831
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003832 if (cursorRange.isInvalid())
3833 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003834
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003835 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3836
Ted Kremeneka333c662010-05-12 05:29:33 +00003837 // Adjust the annotated range based specific declarations.
3838 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3839 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003840 Decl *D = cxcursor::getCursorDecl(cursor);
3841 // Don't visit synthesized ObjC methods, since they have no syntatic
3842 // representation in the source.
3843 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3844 if (MD->isSynthesized())
3845 return CXChildVisit_Continue;
3846 }
3847 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003848 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3849 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003850 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003851 if (TLoc.isValid() &&
3852 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003853 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003854 }
3855 }
3856 }
3857
Ted Kremenek3f404602010-08-14 01:14:06 +00003858 // If the location of the cursor occurs within a macro instantiation, record
3859 // the spelling location of the cursor in our annotation map. We can then
3860 // paper over the token labelings during a post-processing step to try and
3861 // get cursor mappings for tokens that are the *arguments* of a macro
3862 // instantiation.
3863 if (L.isMacroID()) {
3864 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3865 // Only invalidate the old annotation if it isn't part of a preprocessing
3866 // directive. Here we assume that the default construction of CXCursor
3867 // results in CXCursor.kind being an initialized value (i.e., 0). If
3868 // this isn't the case, we can fix by doing lookup + insertion.
3869
3870 CXCursor &oldC = Annotated[rawEncoding];
3871 if (!clang_isPreprocessing(oldC.kind))
3872 oldC = cursor;
3873 }
3874
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003875 const enum CXCursorKind K = clang_getCursorKind(parent);
3876 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003877 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3878 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003879
3880 while (MoreTokens()) {
3881 const unsigned I = NextToken();
3882 SourceLocation TokLoc = GetTokenLoc(I);
3883 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3884 case RangeBefore:
3885 Cursors[I] = updateC;
3886 AdvanceToken();
3887 continue;
3888 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003889 case RangeOverlap:
3890 break;
3891 }
3892 break;
3893 }
3894
3895 // Visit children to get their cursor information.
3896 const unsigned BeforeChildren = NextToken();
3897 VisitChildren(cursor);
3898 const unsigned AfterChildren = NextToken();
3899
3900 // Adjust 'Last' to the last token within the extent of the cursor.
3901 while (MoreTokens()) {
3902 const unsigned I = NextToken();
3903 SourceLocation TokLoc = GetTokenLoc(I);
3904 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3905 case RangeBefore:
3906 assert(0 && "Infeasible");
3907 case RangeAfter:
3908 break;
3909 case RangeOverlap:
3910 Cursors[I] = updateC;
3911 AdvanceToken();
3912 continue;
3913 }
3914 break;
3915 }
3916 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003917
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003918 // Scan the tokens that are at the beginning of the cursor, but are not
3919 // capture by the child cursors.
3920
3921 // For AST elements within macros, rely on a post-annotate pass to
3922 // to correctly annotate the tokens with cursors. Otherwise we can
3923 // get confusing results of having tokens that map to cursors that really
3924 // are expanded by an instantiation.
3925 if (L.isMacroID())
3926 cursor = clang_getNullCursor();
3927
3928 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3929 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3930 break;
3931 Cursors[I] = cursor;
3932 }
3933 // Scan the tokens that are at the end of the cursor, but are not captured
3934 // but the child cursors.
3935 for (unsigned I = AfterChildren; I != Last; ++I)
3936 Cursors[I] = cursor;
3937
3938 TokIdx = Last;
3939 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003940}
3941
Ted Kremenek6db61092010-05-05 00:55:15 +00003942static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3943 CXCursor parent,
3944 CXClientData client_data) {
3945 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3946}
3947
3948extern "C" {
3949
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003950void clang_annotateTokens(CXTranslationUnit TU,
3951 CXToken *Tokens, unsigned NumTokens,
3952 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003953
3954 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003955 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003956
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003957 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003958 if (!CXXUnit) {
3959 // Any token we don't specifically annotate will have a NULL cursor.
3960 const CXCursor &C = clang_getNullCursor();
3961 for (unsigned I = 0; I != NumTokens; ++I)
3962 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003963 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003964 }
3965
Douglas Gregorbdf60622010-03-05 21:16:25 +00003966 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003967
Douglas Gregor0396f462010-03-19 05:22:59 +00003968 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003969 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003970 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3971 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003972 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3973 clang_getTokenLocation(TU,
3974 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003975
Douglas Gregor0396f462010-03-19 05:22:59 +00003976 // A mapping from the source locations found when re-lexing or traversing the
3977 // region of interest to the corresponding cursors.
3978 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003979
3980 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003981 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003982 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3983 std::pair<FileID, unsigned> BeginLocInfo
3984 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3985 std::pair<FileID, unsigned> EndLocInfo
3986 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003987
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003988 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003989 bool Invalid = false;
3990 if (BeginLocInfo.first == EndLocInfo.first &&
3991 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3992 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003993 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3994 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003995 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003996 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003997 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003998
3999 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004000 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004001 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004002 Token Tok;
4003 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004004
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004005 reprocess:
4006 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4007 // We have found a preprocessing directive. Gobble it up so that we
4008 // don't see it while preprocessing these tokens later, but keep track of
4009 // all of the token locations inside this preprocessing directive so that
4010 // we can annotate them appropriately.
4011 //
4012 // FIXME: Some simple tests here could identify macro definitions and
4013 // #undefs, to provide specific cursor kinds for those.
4014 std::vector<SourceLocation> Locations;
4015 do {
4016 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004017 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004018 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004019
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004020 using namespace cxcursor;
4021 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004022 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4023 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004024 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004025 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4026 Annotated[Locations[I].getRawEncoding()] = Cursor;
4027 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004028
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004029 if (Tok.isAtStartOfLine())
4030 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004031
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004032 continue;
4033 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004034
Douglas Gregor48072312010-03-18 15:23:44 +00004035 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004036 break;
4037 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004038 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004039
Douglas Gregor0396f462010-03-19 05:22:59 +00004040 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004041 // a specific cursor.
4042 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4043 CXXUnit, RegionOfInterest);
4044 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004045}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004046} // end: extern "C"
4047
4048//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004049// Operations for querying linkage of a cursor.
4050//===----------------------------------------------------------------------===//
4051
4052extern "C" {
4053CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004054 if (!clang_isDeclaration(cursor.kind))
4055 return CXLinkage_Invalid;
4056
Ted Kremenek16b42592010-03-03 06:36:57 +00004057 Decl *D = cxcursor::getCursorDecl(cursor);
4058 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4059 switch (ND->getLinkage()) {
4060 case NoLinkage: return CXLinkage_NoLinkage;
4061 case InternalLinkage: return CXLinkage_Internal;
4062 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4063 case ExternalLinkage: return CXLinkage_External;
4064 };
4065
4066 return CXLinkage_Invalid;
4067}
4068} // end: extern "C"
4069
4070//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004071// Operations for querying language of a cursor.
4072//===----------------------------------------------------------------------===//
4073
4074static CXLanguageKind getDeclLanguage(const Decl *D) {
4075 switch (D->getKind()) {
4076 default:
4077 break;
4078 case Decl::ImplicitParam:
4079 case Decl::ObjCAtDefsField:
4080 case Decl::ObjCCategory:
4081 case Decl::ObjCCategoryImpl:
4082 case Decl::ObjCClass:
4083 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004084 case Decl::ObjCForwardProtocol:
4085 case Decl::ObjCImplementation:
4086 case Decl::ObjCInterface:
4087 case Decl::ObjCIvar:
4088 case Decl::ObjCMethod:
4089 case Decl::ObjCProperty:
4090 case Decl::ObjCPropertyImpl:
4091 case Decl::ObjCProtocol:
4092 return CXLanguage_ObjC;
4093 case Decl::CXXConstructor:
4094 case Decl::CXXConversion:
4095 case Decl::CXXDestructor:
4096 case Decl::CXXMethod:
4097 case Decl::CXXRecord:
4098 case Decl::ClassTemplate:
4099 case Decl::ClassTemplatePartialSpecialization:
4100 case Decl::ClassTemplateSpecialization:
4101 case Decl::Friend:
4102 case Decl::FriendTemplate:
4103 case Decl::FunctionTemplate:
4104 case Decl::LinkageSpec:
4105 case Decl::Namespace:
4106 case Decl::NamespaceAlias:
4107 case Decl::NonTypeTemplateParm:
4108 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004109 case Decl::TemplateTemplateParm:
4110 case Decl::TemplateTypeParm:
4111 case Decl::UnresolvedUsingTypename:
4112 case Decl::UnresolvedUsingValue:
4113 case Decl::Using:
4114 case Decl::UsingDirective:
4115 case Decl::UsingShadow:
4116 return CXLanguage_CPlusPlus;
4117 }
4118
4119 return CXLanguage_C;
4120}
4121
4122extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004123
4124enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4125 if (clang_isDeclaration(cursor.kind))
4126 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4127 if (D->hasAttr<UnavailableAttr>() ||
4128 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4129 return CXAvailability_Available;
4130
4131 if (D->hasAttr<DeprecatedAttr>())
4132 return CXAvailability_Deprecated;
4133 }
4134
4135 return CXAvailability_Available;
4136}
4137
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004138CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4139 if (clang_isDeclaration(cursor.kind))
4140 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4141
4142 return CXLanguage_Invalid;
4143}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004144
4145CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4146 if (clang_isDeclaration(cursor.kind)) {
4147 if (Decl *D = getCursorDecl(cursor)) {
4148 DeclContext *DC = D->getDeclContext();
4149 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4150 }
4151 }
4152
4153 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4154 if (Decl *D = getCursorDecl(cursor))
4155 return MakeCXCursor(D, getCursorASTUnit(cursor));
4156 }
4157
4158 return clang_getNullCursor();
4159}
4160
4161CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4162 if (clang_isDeclaration(cursor.kind)) {
4163 if (Decl *D = getCursorDecl(cursor)) {
4164 DeclContext *DC = D->getLexicalDeclContext();
4165 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4166 }
4167 }
4168
4169 // FIXME: Note that we can't easily compute the lexical context of a
4170 // statement or expression, so we return nothing.
4171 return clang_getNullCursor();
4172}
4173
Douglas Gregor9f592342010-10-01 20:25:15 +00004174static void CollectOverriddenMethods(DeclContext *Ctx,
4175 ObjCMethodDecl *Method,
4176 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4177 if (!Ctx)
4178 return;
4179
4180 // If we have a class or category implementation, jump straight to the
4181 // interface.
4182 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4183 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4184
4185 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4186 if (!Container)
4187 return;
4188
4189 // Check whether we have a matching method at this level.
4190 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4191 Method->isInstanceMethod()))
4192 if (Method != Overridden) {
4193 // We found an override at this level; there is no need to look
4194 // into other protocols or categories.
4195 Methods.push_back(Overridden);
4196 return;
4197 }
4198
4199 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4200 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4201 PEnd = Protocol->protocol_end();
4202 P != PEnd; ++P)
4203 CollectOverriddenMethods(*P, Method, Methods);
4204 }
4205
4206 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4207 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4208 PEnd = Category->protocol_end();
4209 P != PEnd; ++P)
4210 CollectOverriddenMethods(*P, Method, Methods);
4211 }
4212
4213 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4214 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4215 PEnd = Interface->protocol_end();
4216 P != PEnd; ++P)
4217 CollectOverriddenMethods(*P, Method, Methods);
4218
4219 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4220 Category; Category = Category->getNextClassCategory())
4221 CollectOverriddenMethods(Category, Method, Methods);
4222
4223 // We only look into the superclass if we haven't found anything yet.
4224 if (Methods.empty())
4225 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4226 return CollectOverriddenMethods(Super, Method, Methods);
4227 }
4228}
4229
4230void clang_getOverriddenCursors(CXCursor cursor,
4231 CXCursor **overridden,
4232 unsigned *num_overridden) {
4233 if (overridden)
4234 *overridden = 0;
4235 if (num_overridden)
4236 *num_overridden = 0;
4237 if (!overridden || !num_overridden)
4238 return;
4239
4240 if (!clang_isDeclaration(cursor.kind))
4241 return;
4242
4243 Decl *D = getCursorDecl(cursor);
4244 if (!D)
4245 return;
4246
4247 // Handle C++ member functions.
4248 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4249 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4250 *num_overridden = CXXMethod->size_overridden_methods();
4251 if (!*num_overridden)
4252 return;
4253
4254 *overridden = new CXCursor [*num_overridden];
4255 unsigned I = 0;
4256 for (CXXMethodDecl::method_iterator
4257 M = CXXMethod->begin_overridden_methods(),
4258 MEnd = CXXMethod->end_overridden_methods();
4259 M != MEnd; (void)++M, ++I)
4260 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4261 return;
4262 }
4263
4264 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4265 if (!Method)
4266 return;
4267
4268 // Handle Objective-C methods.
4269 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4270 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4271
4272 if (Methods.empty())
4273 return;
4274
4275 *num_overridden = Methods.size();
4276 *overridden = new CXCursor [Methods.size()];
4277 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4278 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4279}
4280
4281void clang_disposeOverriddenCursors(CXCursor *overridden) {
4282 delete [] overridden;
4283}
4284
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004285} // end: extern "C"
4286
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004287
4288//===----------------------------------------------------------------------===//
4289// C++ AST instrospection.
4290//===----------------------------------------------------------------------===//
4291
4292extern "C" {
4293unsigned clang_CXXMethod_isStatic(CXCursor C) {
4294 if (!clang_isDeclaration(C.kind))
4295 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004296
4297 CXXMethodDecl *Method = 0;
4298 Decl *D = cxcursor::getCursorDecl(C);
4299 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4300 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4301 else
4302 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4303 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004304}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004305
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004306} // end: extern "C"
4307
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004308//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004309// Attribute introspection.
4310//===----------------------------------------------------------------------===//
4311
4312extern "C" {
4313CXType clang_getIBOutletCollectionType(CXCursor C) {
4314 if (C.kind != CXCursor_IBOutletCollectionAttr)
4315 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4316
4317 IBOutletCollectionAttr *A =
4318 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4319
4320 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4321}
4322} // end: extern "C"
4323
4324//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004325// CXString Operations.
4326//===----------------------------------------------------------------------===//
4327
4328extern "C" {
4329const char *clang_getCString(CXString string) {
4330 return string.Spelling;
4331}
4332
4333void clang_disposeString(CXString string) {
4334 if (string.MustFreeString && string.Spelling)
4335 free((void*)string.Spelling);
4336}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004337
Ted Kremenekfb480492010-01-13 21:46:36 +00004338} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004339
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004340namespace clang { namespace cxstring {
4341CXString createCXString(const char *String, bool DupString){
4342 CXString Str;
4343 if (DupString) {
4344 Str.Spelling = strdup(String);
4345 Str.MustFreeString = 1;
4346 } else {
4347 Str.Spelling = String;
4348 Str.MustFreeString = 0;
4349 }
4350 return Str;
4351}
4352
4353CXString createCXString(llvm::StringRef String, bool DupString) {
4354 CXString Result;
4355 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4356 char *Spelling = (char *)malloc(String.size() + 1);
4357 memmove(Spelling, String.data(), String.size());
4358 Spelling[String.size()] = 0;
4359 Result.Spelling = Spelling;
4360 Result.MustFreeString = 1;
4361 } else {
4362 Result.Spelling = String.data();
4363 Result.MustFreeString = 0;
4364 }
4365 return Result;
4366}
4367}}
4368
Ted Kremenek04bb7162010-01-22 22:44:15 +00004369//===----------------------------------------------------------------------===//
4370// Misc. utility functions.
4371//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004372
Ted Kremenek04bb7162010-01-22 22:44:15 +00004373extern "C" {
4374
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004375CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004376 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004377}
4378
4379} // end: extern "C"