blob: 1dfabcac65732619a767ecffb5c23a6f4f8757d2 [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"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000035#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000036#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000037#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000038#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000039#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000040#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000041#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000042#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000043
Benjamin Kramerc2a98162010-03-13 21:22:49 +000044// Needed to define L_TMPNAM on some systems.
45#include <cstdio>
46
Steve Naroff50398192009-08-28 15:28:48 +000047using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000048using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000049using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000050
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000051//===----------------------------------------------------------------------===//
52// Crash Reporting.
53//===----------------------------------------------------------------------===//
54
Ted Kremenekd7ffd082010-05-22 00:06:46 +000055#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000056#include "clang/Analysis/Support/SaveAndRestore.h"
57// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000058static const char *__crashreporter_info__ = 0;
59asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000060#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000061static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000062static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000063static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
64static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
65
66static unsigned SetCrashTracerInfo(const char *str,
67 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000068
Ted Kremenek254ba7c2010-01-07 23:13:53 +000069 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000070 while (crashtracer_strings[slot]) {
71 if (++slot == NUM_CRASH_STRINGS)
72 slot = 0;
73 }
74 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000075 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000076
77 // We need to create an aggregate string because multiple threads
78 // may be in this method at one time. The crash reporter string
79 // will attempt to overapproximate the set of in-flight invocations
80 // of this function. Race conditions can still cause this goal
81 // to not be achieved.
82 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000083 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000084 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
85 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
86 }
87 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
88 return slot;
89}
90
91static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000092 unsigned max_slot = 0;
93 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000094
Ted Kremenek254ba7c2010-01-07 23:13:53 +000095 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
96
97 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
98 if (agg_crashtracer_strings[i] &&
99 crashtracer_counter_id[i] > max_value) {
100 max_slot = i;
101 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +0000102 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +0000103
104 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +0000105}
106
107namespace {
108class ArgsCrashTracerInfo {
109 llvm::SmallString<1024> CrashString;
110 llvm::SmallString<1024> AggregateString;
111 unsigned crashtracerSlot;
112public:
113 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
114 : crashtracerSlot(0)
115 {
116 {
117 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000118 Out << "ClangCIndex [" << getClangFullVersion() << "]"
119 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000120 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
121 E=Args.end(); I!=E; ++I)
122 Out << ' ' << *I;
123 }
124 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
125 AggregateString);
126 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000127
Ted Kremenek29b72842010-01-07 22:49:05 +0000128 ~ArgsCrashTracerInfo() {
129 ResetCrashTracerInfo(crashtracerSlot);
130 }
131};
132}
133#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135/// \brief The result of comparing two source ranges.
136enum RangeComparisonResult {
137 /// \brief Either the ranges overlap or one of the ranges is invalid.
138 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000139
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000140 /// \brief The first range ends before the second range starts.
141 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000142
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000143 /// \brief The first range starts after the second range ends.
144 RangeAfter
145};
146
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000147/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000149static RangeComparisonResult RangeCompare(SourceManager &SM,
150 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151 SourceRange R2) {
152 assert(R1.isValid() && "First range is invalid?");
153 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000154 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000155 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000156 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000157 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000158 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000159 return RangeAfter;
160 return RangeOverlap;
161}
162
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000163/// \brief Determine if a source location falls within, before, or after a
164/// a given source range.
165static RangeComparisonResult LocationCompare(SourceManager &SM,
166 SourceLocation L, SourceRange R) {
167 assert(R.isValid() && "First range is invalid?");
168 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000169 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000170 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000171 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
172 return RangeBefore;
173 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
174 return RangeAfter;
175 return RangeOverlap;
176}
177
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000178/// \brief Translate a Clang source range into a CIndex source range.
179///
180/// Clang internally represents ranges where the end location points to the
181/// start of the token at the end. However, for external clients it is more
182/// useful to have a CXSourceRange be a proper half-open interval. This routine
183/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000184CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000185 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000186 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000187 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000188 // location accordingly.
189 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000190 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000191 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000192 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000193 EndLoc = EndLoc.getFileLocWithOffset(Length);
194 }
195
196 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
197 R.getBegin().getRawEncoding(),
198 EndLoc.getRawEncoding() };
199 return Result;
200}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000201
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000202//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000203// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000204//===----------------------------------------------------------------------===//
205
Steve Naroff89922f82009-08-31 00:59:03 +0000206namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000207
Douglas Gregorb1373d02010-01-20 20:59:29 +0000208// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000209class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000210 public TypeLocVisitor<CursorVisitor, bool>,
211 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000212{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000213 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000214 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000215
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000216 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000217 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000218
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000219 /// \brief The declaration that serves at the parent of any statement or
220 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000221 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000222
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000223 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000224 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000225
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000226 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000227 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000228
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000229 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
230 // to the visitor. Declarations with a PCH level greater than this value will
231 // be suppressed.
232 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000233
234 /// \brief When valid, a source range to which the cursor should restrict
235 /// its search.
236 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000237
Douglas Gregorb1373d02010-01-20 20:59:29 +0000238 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000239 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000240 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000241
242 /// \brief Determine whether this particular source range comes before, comes
243 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000244 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000245 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000246 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
247
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000248 class SetParentRAII {
249 CXCursor &Parent;
250 Decl *&StmtParent;
251 CXCursor OldParent;
252
253 public:
254 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
255 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
256 {
257 Parent = NewParent;
258 if (clang_isDeclaration(Parent.kind))
259 StmtParent = getCursorDecl(Parent);
260 }
261
262 ~SetParentRAII() {
263 Parent = OldParent;
264 if (clang_isDeclaration(Parent.kind))
265 StmtParent = getCursorDecl(Parent);
266 }
267 };
268
Steve Naroff89922f82009-08-31 00:59:03 +0000269public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000270 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
271 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000272 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000273 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000274 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000275 {
276 Parent.kind = CXCursor_NoDeclFound;
277 Parent.data[0] = 0;
278 Parent.data[1] = 0;
279 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000280 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000281 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000282
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000283 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000284
285 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
286 getPreprocessedEntities();
287
Douglas Gregorb1373d02010-01-20 20:59:29 +0000288 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000289
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000290 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000291 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000292 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000293 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000294 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000295 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
296 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000297 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000298 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000299 bool VisitClassTemplatePartialSpecializationDecl(
300 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000301 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000302 bool VisitEnumConstantDecl(EnumConstantDecl *D);
303 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
304 bool VisitFunctionDecl(FunctionDecl *ND);
305 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000306 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000307 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000308 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000309 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000310 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000311 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
312 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
313 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
314 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000315 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000316 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
317 bool VisitObjCImplDecl(ObjCImplDecl *D);
318 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
319 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000320 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
321 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
322 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000323 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000324 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000325 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000326 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000327 bool VisitUsingDecl(UsingDecl *D);
328 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
329 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000330
Douglas Gregor01829d32010-08-31 14:41:23 +0000331 // Name visitor
332 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000333 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000334
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000335 // Template visitors
336 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000337 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000338 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
339
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000340 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000341 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000342 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000343 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000344 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
345 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000346 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000347 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000348 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000349 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
350 bool VisitPointerTypeLoc(PointerTypeLoc TL);
351 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
352 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
353 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
354 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000355 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000356 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000357 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000358 // FIXME: Implement visitors here when the unimplemented TypeLocs get
359 // implemented
360 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
361 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000362
Douglas Gregora59e3902010-01-21 23:27:09 +0000363 // Statement visitors
364 bool VisitStmt(Stmt *S);
365 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000366 bool VisitGotoStmt(GotoStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000367 bool VisitIfStmt(IfStmt *S);
368 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000369 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000370 bool VisitWhileStmt(WhileStmt *S);
371 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000372
Douglas Gregor336fd812010-01-23 00:40:08 +0000373 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000374 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000375 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000376 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000377 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000378 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000379 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000380 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000381 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000382 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfbb4c982010-09-02 21:07:44 +0000383 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000384 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000385 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
386 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000387 bool VisitInitListExpr(InitListExpr *E);
388 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000389 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000390 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000391 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000392 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
393 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000394 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000395 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000396 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000397 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000398 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000399 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000400 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000401 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000402};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000403
Ted Kremenekab188932010-01-05 19:32:54 +0000404} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000405
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000406static SourceRange getRawCursorExtent(CXCursor C);
407
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000408RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000409 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
410}
411
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412/// \brief Visit the given cursor and, if requested by the visitor,
413/// its children.
414///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000415/// \param Cursor the cursor to visit.
416///
417/// \param CheckRegionOfInterest if true, then the caller already checked that
418/// this cursor is within the region of interest.
419///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000420/// \returns true if the visitation should be aborted, false if it
421/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000422bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000423 if (clang_isInvalid(Cursor.kind))
424 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000425
Douglas Gregorb1373d02010-01-20 20:59:29 +0000426 if (clang_isDeclaration(Cursor.kind)) {
427 Decl *D = getCursorDecl(Cursor);
428 assert(D && "Invalid declaration cursor");
429 if (D->getPCHLevel() > MaxPCHLevel)
430 return false;
431
432 if (D->isImplicit())
433 return false;
434 }
435
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000436 // If we have a range of interest, and this cursor doesn't intersect with it,
437 // we're done.
438 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000439 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000440 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000441 return false;
442 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000443
Douglas Gregorb1373d02010-01-20 20:59:29 +0000444 switch (Visitor(Cursor, Parent, ClientData)) {
445 case CXChildVisit_Break:
446 return true;
447
448 case CXChildVisit_Continue:
449 return false;
450
451 case CXChildVisit_Recurse:
452 return VisitChildren(Cursor);
453 }
454
Douglas Gregorfd643772010-01-25 16:45:46 +0000455 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000456}
457
Douglas Gregor788f5a12010-03-20 00:41:21 +0000458std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
459CursorVisitor::getPreprocessedEntities() {
460 PreprocessingRecord &PPRec
461 = *TU->getPreprocessor().getPreprocessingRecord();
462
463 bool OnlyLocalDecls
464 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
465
466 // There is no region of interest; we have to walk everything.
467 if (RegionOfInterest.isInvalid())
468 return std::make_pair(PPRec.begin(OnlyLocalDecls),
469 PPRec.end(OnlyLocalDecls));
470
471 // Find the file in which the region of interest lands.
472 SourceManager &SM = TU->getSourceManager();
473 std::pair<FileID, unsigned> Begin
474 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
475 std::pair<FileID, unsigned> End
476 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
477
478 // The region of interest spans files; we have to walk everything.
479 if (Begin.first != End.first)
480 return std::make_pair(PPRec.begin(OnlyLocalDecls),
481 PPRec.end(OnlyLocalDecls));
482
483 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
484 = TU->getPreprocessedEntitiesByFile();
485 if (ByFileMap.empty()) {
486 // Build the mapping from files to sets of preprocessed entities.
487 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
488 EEnd = PPRec.end(OnlyLocalDecls);
489 E != EEnd; ++E) {
490 std::pair<FileID, unsigned> P
491 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
492 ByFileMap[P.first].push_back(*E);
493 }
494 }
495
496 return std::make_pair(ByFileMap[Begin.first].begin(),
497 ByFileMap[Begin.first].end());
498}
499
Douglas Gregorb1373d02010-01-20 20:59:29 +0000500/// \brief Visit the children of the given cursor.
501///
502/// \returns true if the visitation should be aborted, false if it
503/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000504bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000505 if (clang_isReference(Cursor.kind)) {
506 // By definition, references have no children.
507 return false;
508 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000509
510 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000511 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000512 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000513
Douglas Gregorb1373d02010-01-20 20:59:29 +0000514 if (clang_isDeclaration(Cursor.kind)) {
515 Decl *D = getCursorDecl(Cursor);
516 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000517 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000518 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000519
Douglas Gregora59e3902010-01-21 23:27:09 +0000520 if (clang_isStatement(Cursor.kind))
521 return Visit(getCursorStmt(Cursor));
522 if (clang_isExpression(Cursor.kind))
523 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000524
Douglas Gregorb1373d02010-01-20 20:59:29 +0000525 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000526 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000527 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
528 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000529 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
530 TLEnd = CXXUnit->top_level_end();
531 TL != TLEnd; ++TL) {
532 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000533 return true;
534 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000535 } else if (VisitDeclContext(
536 CXXUnit->getASTContext().getTranslationUnitDecl()))
537 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000538
Douglas Gregor0396f462010-03-19 05:22:59 +0000539 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000540 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000541 // FIXME: Once we have the ability to deserialize a preprocessing record,
542 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000543 PreprocessingRecord::iterator E, EEnd;
544 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000545 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
546 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
547 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000548
Douglas Gregor0396f462010-03-19 05:22:59 +0000549 continue;
550 }
551
552 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
553 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
554 return true;
555
556 continue;
557 }
558 }
559 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000560 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000561 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000562
Douglas Gregorb1373d02010-01-20 20:59:29 +0000563 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000564 return false;
565}
566
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000567bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000568 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
569 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000570
Ted Kremenek664cffd2010-07-22 11:30:19 +0000571 if (Stmt *Body = B->getBody())
572 return Visit(MakeCXCursor(Body, StmtParent, TU));
573
574 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000575}
576
Douglas Gregorb1373d02010-01-20 20:59:29 +0000577bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000578 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000579 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000580
Ted Kremenek23173d72010-05-18 21:09:07 +0000581 Decl *D = *I;
582 if (D->getLexicalDeclContext() != DC)
583 continue;
584
585 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000586
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000587 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000588 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000589 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000590 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000591
592 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000593 case RangeBefore:
594 // This declaration comes before the region of interest; skip it.
595 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000596
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000597 case RangeAfter:
598 // This declaration comes after the region of interest; we're done.
599 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000600
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000601 case RangeOverlap:
602 // This declaration overlaps the region of interest; visit it.
603 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000604 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000605 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000606
Daniel Dunbard52864b2010-02-14 10:02:57 +0000607 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000608 return true;
609 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000610
Douglas Gregorb1373d02010-01-20 20:59:29 +0000611 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000612}
613
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000614bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
615 llvm_unreachable("Translation units are visited directly by Visit()");
616 return false;
617}
618
619bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
620 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
621 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000622
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000623 return false;
624}
625
626bool CursorVisitor::VisitTagDecl(TagDecl *D) {
627 return VisitDeclContext(D);
628}
629
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000630bool CursorVisitor::VisitClassTemplateSpecializationDecl(
631 ClassTemplateSpecializationDecl *D) {
632 bool ShouldVisitBody = false;
633 switch (D->getSpecializationKind()) {
634 case TSK_Undeclared:
635 case TSK_ImplicitInstantiation:
636 // Nothing to visit
637 return false;
638
639 case TSK_ExplicitInstantiationDeclaration:
640 case TSK_ExplicitInstantiationDefinition:
641 break;
642
643 case TSK_ExplicitSpecialization:
644 ShouldVisitBody = true;
645 break;
646 }
647
648 // Visit the template arguments used in the specialization.
649 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
650 TypeLoc TL = SpecType->getTypeLoc();
651 if (TemplateSpecializationTypeLoc *TSTLoc
652 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
653 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
654 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
655 return true;
656 }
657 }
658
659 if (ShouldVisitBody && VisitCXXRecordDecl(D))
660 return true;
661
662 return false;
663}
664
Douglas Gregor74dbe642010-08-31 19:31:58 +0000665bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
666 ClassTemplatePartialSpecializationDecl *D) {
667 // FIXME: Visit the "outer" template parameter lists on the TagDecl
668 // before visiting these template parameters.
669 if (VisitTemplateParameters(D->getTemplateParameters()))
670 return true;
671
672 // Visit the partial specialization arguments.
673 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
674 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
675 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
676 return true;
677
678 return VisitCXXRecordDecl(D);
679}
680
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000681bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000682 // Visit the default argument.
683 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
684 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
685 if (Visit(DefArg->getTypeLoc()))
686 return true;
687
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000688 return false;
689}
690
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000691bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
692 if (Expr *Init = D->getInitExpr())
693 return Visit(MakeCXCursor(Init, StmtParent, TU));
694 return false;
695}
696
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000697bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
698 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
699 if (Visit(TSInfo->getTypeLoc()))
700 return true;
701
702 return false;
703}
704
Douglas Gregora67e03f2010-09-09 21:42:20 +0000705/// \brief Compare two base or member initializers based on their source order.
706static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
707 CXXBaseOrMemberInitializer const * const *X
708 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
709 CXXBaseOrMemberInitializer const * const *Y
710 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
711
712 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
713 return -1;
714 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
715 return 1;
716 else
717 return 0;
718}
719
Douglas Gregorb1373d02010-01-20 20:59:29 +0000720bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000721 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
722 // Visit the function declaration's syntactic components in the order
723 // written. This requires a bit of work.
724 TypeLoc TL = TSInfo->getTypeLoc();
725 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
726
727 // If we have a function declared directly (without the use of a typedef),
728 // visit just the return type. Otherwise, just visit the function's type
729 // now.
730 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
731 (!FTL && Visit(TL)))
732 return true;
733
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000734 // Visit the nested-name-specifier, if present.
735 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
736 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
737 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000738
739 // Visit the declaration name.
740 if (VisitDeclarationNameInfo(ND->getNameInfo()))
741 return true;
742
743 // FIXME: Visit explicitly-specified template arguments!
744
745 // Visit the function parameters, if we have a function type.
746 if (FTL && VisitFunctionTypeLoc(*FTL, true))
747 return true;
748
749 // FIXME: Attributes?
750 }
751
Douglas Gregora67e03f2010-09-09 21:42:20 +0000752 if (ND->isThisDeclarationADefinition()) {
753 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
754 // Find the initializers that were written in the source.
755 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
756 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
757 IEnd = Constructor->init_end();
758 I != IEnd; ++I) {
759 if (!(*I)->isWritten())
760 continue;
761
762 WrittenInits.push_back(*I);
763 }
764
765 // Sort the initializers in source order
766 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
767 &CompareCXXBaseOrMemberInitializers);
768
769 // Visit the initializers in source order
770 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
771 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
772 if (Init->isMemberInitializer()) {
773 if (Visit(MakeCursorMemberRef(Init->getMember(),
774 Init->getMemberLocation(), TU)))
775 return true;
776 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
777 if (Visit(BaseInfo->getTypeLoc()))
778 return true;
779 }
780
781 // Visit the initializer value.
782 if (Expr *Initializer = Init->getInit())
783 if (Visit(MakeCXCursor(Initializer, ND, TU)))
784 return true;
785 }
786 }
787
788 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
789 return true;
790 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000791
Douglas Gregorb1373d02010-01-20 20:59:29 +0000792 return false;
793}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
796 if (VisitDeclaratorDecl(D))
797 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000798
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000799 if (Expr *BitWidth = D->getBitWidth())
800 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000801
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000802 return false;
803}
804
805bool CursorVisitor::VisitVarDecl(VarDecl *D) {
806 if (VisitDeclaratorDecl(D))
807 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000808
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000809 if (Expr *Init = D->getInit())
810 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000811
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000812 return false;
813}
814
Douglas Gregor84b51d72010-09-01 20:16:53 +0000815bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
816 if (VisitDeclaratorDecl(D))
817 return true;
818
819 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
820 if (Expr *DefArg = D->getDefaultArgument())
821 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
822
823 return false;
824}
825
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000826bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
827 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
828 // before visiting these template parameters.
829 if (VisitTemplateParameters(D->getTemplateParameters()))
830 return true;
831
832 return VisitFunctionDecl(D->getTemplatedDecl());
833}
834
Douglas Gregor39d6f072010-08-31 19:02:00 +0000835bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
836 // FIXME: Visit the "outer" template parameter lists on the TagDecl
837 // before visiting these template parameters.
838 if (VisitTemplateParameters(D->getTemplateParameters()))
839 return true;
840
841 return VisitCXXRecordDecl(D->getTemplatedDecl());
842}
843
Douglas Gregor84b51d72010-09-01 20:16:53 +0000844bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
845 if (VisitTemplateParameters(D->getTemplateParameters()))
846 return true;
847
848 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
849 VisitTemplateArgumentLoc(D->getDefaultArgument()))
850 return true;
851
852 return false;
853}
854
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000855bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000856 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
857 if (Visit(TSInfo->getTypeLoc()))
858 return true;
859
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000860 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000861 PEnd = ND->param_end();
862 P != PEnd; ++P) {
863 if (Visit(MakeCXCursor(*P, TU)))
864 return true;
865 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000866
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000867 if (ND->isThisDeclarationADefinition() &&
868 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
869 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000870
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000871 return false;
872}
873
Douglas Gregora59e3902010-01-21 23:27:09 +0000874bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
875 return VisitDeclContext(D);
876}
877
Douglas Gregorb1373d02010-01-20 20:59:29 +0000878bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000879 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
880 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000881 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000882
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000883 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
884 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
885 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000886 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000887 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000888
Douglas Gregora59e3902010-01-21 23:27:09 +0000889 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000890}
891
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000892bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
893 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
894 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
895 E = PID->protocol_end(); I != E; ++I, ++PL)
896 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
897 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000898
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000899 return VisitObjCContainerDecl(PID);
900}
901
Ted Kremenek23173d72010-05-18 21:09:07 +0000902bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000903 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000904 return true;
905
Ted Kremenek23173d72010-05-18 21:09:07 +0000906 // FIXME: This implements a workaround with @property declarations also being
907 // installed in the DeclContext for the @interface. Eventually this code
908 // should be removed.
909 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
910 if (!CDecl || !CDecl->IsClassExtension())
911 return false;
912
913 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
914 if (!ID)
915 return false;
916
917 IdentifierInfo *PropertyId = PD->getIdentifier();
918 ObjCPropertyDecl *prevDecl =
919 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
920
921 if (!prevDecl)
922 return false;
923
924 // Visit synthesized methods since they will be skipped when visiting
925 // the @interface.
926 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000927 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000928 if (Visit(MakeCXCursor(MD, TU)))
929 return true;
930
931 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000932 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000933 if (Visit(MakeCXCursor(MD, TU)))
934 return true;
935
936 return false;
937}
938
Douglas Gregorb1373d02010-01-20 20:59:29 +0000939bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000940 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000941 if (D->getSuperClass() &&
942 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000943 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000944 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000945 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000946
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000947 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
948 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
949 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000950 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000951 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000952
Douglas Gregora59e3902010-01-21 23:27:09 +0000953 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000954}
955
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000956bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
957 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000958}
959
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000960bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000961 // 'ID' could be null when dealing with invalid code.
962 if (ObjCInterfaceDecl *ID = D->getClassInterface())
963 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
964 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000965
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000966 return VisitObjCImplDecl(D);
967}
968
969bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
970#if 0
971 // Issue callbacks for super class.
972 // FIXME: No source location information!
973 if (D->getSuperClass() &&
974 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000975 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000976 TU)))
977 return true;
978#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000979
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000980 return VisitObjCImplDecl(D);
981}
982
983bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
984 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
985 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
986 E = D->protocol_end();
987 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000988 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000989 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000990
991 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000992}
993
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000994bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
995 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
996 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
997 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000998
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000999 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001000}
1001
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001002bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1003 return VisitDeclContext(D);
1004}
1005
Douglas Gregor69319002010-08-31 23:48:11 +00001006bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001007 // Visit nested-name-specifier.
1008 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1009 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1010 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001011
1012 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1013 D->getTargetNameLoc(), TU));
1014}
1015
Douglas Gregor7e242562010-09-01 19:52:22 +00001016bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001017 // Visit nested-name-specifier.
1018 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1019 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1020 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001021
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001022 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1023 return true;
1024
Douglas Gregor7e242562010-09-01 19:52:22 +00001025 return VisitDeclarationNameInfo(D->getNameInfo());
1026}
1027
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001028bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001029 // Visit nested-name-specifier.
1030 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1031 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1032 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001033
1034 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1035 D->getIdentLocation(), TU));
1036}
1037
Douglas Gregor7e242562010-09-01 19:52:22 +00001038bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001039 // Visit nested-name-specifier.
1040 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1041 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1042 return true;
1043
Douglas Gregor7e242562010-09-01 19:52:22 +00001044 return VisitDeclarationNameInfo(D->getNameInfo());
1045}
1046
1047bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1048 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001049 // Visit nested-name-specifier.
1050 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1051 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1052 return true;
1053
Douglas Gregor7e242562010-09-01 19:52:22 +00001054 return false;
1055}
1056
Douglas Gregor01829d32010-08-31 14:41:23 +00001057bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1058 switch (Name.getName().getNameKind()) {
1059 case clang::DeclarationName::Identifier:
1060 case clang::DeclarationName::CXXLiteralOperatorName:
1061 case clang::DeclarationName::CXXOperatorName:
1062 case clang::DeclarationName::CXXUsingDirective:
1063 return false;
1064
1065 case clang::DeclarationName::CXXConstructorName:
1066 case clang::DeclarationName::CXXDestructorName:
1067 case clang::DeclarationName::CXXConversionFunctionName:
1068 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1069 return Visit(TSInfo->getTypeLoc());
1070 return false;
1071
1072 case clang::DeclarationName::ObjCZeroArgSelector:
1073 case clang::DeclarationName::ObjCOneArgSelector:
1074 case clang::DeclarationName::ObjCMultiArgSelector:
1075 // FIXME: Per-identifier location info?
1076 return false;
1077 }
1078
1079 return false;
1080}
1081
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001082bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1083 SourceRange Range) {
1084 // FIXME: This whole routine is a hack to work around the lack of proper
1085 // source information in nested-name-specifiers (PR5791). Since we do have
1086 // a beginning source location, we can visit the first component of the
1087 // nested-name-specifier, if it's a single-token component.
1088 if (!NNS)
1089 return false;
1090
1091 // Get the first component in the nested-name-specifier.
1092 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1093 NNS = Prefix;
1094
1095 switch (NNS->getKind()) {
1096 case NestedNameSpecifier::Namespace:
1097 // FIXME: The token at this source location might actually have been a
1098 // namespace alias, but we don't model that. Lame!
1099 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1100 TU));
1101
1102 case NestedNameSpecifier::TypeSpec: {
1103 // If the type has a form where we know that the beginning of the source
1104 // range matches up with a reference cursor. Visit the appropriate reference
1105 // cursor.
1106 Type *T = NNS->getAsType();
1107 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1108 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1109 if (const TagType *Tag = dyn_cast<TagType>(T))
1110 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1111 if (const TemplateSpecializationType *TST
1112 = dyn_cast<TemplateSpecializationType>(T))
1113 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1114 break;
1115 }
1116
1117 case NestedNameSpecifier::TypeSpecWithTemplate:
1118 case NestedNameSpecifier::Global:
1119 case NestedNameSpecifier::Identifier:
1120 break;
1121 }
1122
1123 return false;
1124}
1125
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001126bool CursorVisitor::VisitTemplateParameters(
1127 const TemplateParameterList *Params) {
1128 if (!Params)
1129 return false;
1130
1131 for (TemplateParameterList::const_iterator P = Params->begin(),
1132 PEnd = Params->end();
1133 P != PEnd; ++P) {
1134 if (Visit(MakeCXCursor(*P, TU)))
1135 return true;
1136 }
1137
1138 return false;
1139}
1140
Douglas Gregor0b36e612010-08-31 20:37:03 +00001141bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1142 switch (Name.getKind()) {
1143 case TemplateName::Template:
1144 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1145
1146 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001147 // Visit the overloaded template set.
1148 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1149 return true;
1150
Douglas Gregor0b36e612010-08-31 20:37:03 +00001151 return false;
1152
1153 case TemplateName::DependentTemplate:
1154 // FIXME: Visit nested-name-specifier.
1155 return false;
1156
1157 case TemplateName::QualifiedTemplate:
1158 // FIXME: Visit nested-name-specifier.
1159 return Visit(MakeCursorTemplateRef(
1160 Name.getAsQualifiedTemplateName()->getDecl(),
1161 Loc, TU));
1162 }
1163
1164 return false;
1165}
1166
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001167bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1168 switch (TAL.getArgument().getKind()) {
1169 case TemplateArgument::Null:
1170 case TemplateArgument::Integral:
1171 return false;
1172
1173 case TemplateArgument::Pack:
1174 // FIXME: Implement when variadic templates come along.
1175 return false;
1176
1177 case TemplateArgument::Type:
1178 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1179 return Visit(TSInfo->getTypeLoc());
1180 return false;
1181
1182 case TemplateArgument::Declaration:
1183 if (Expr *E = TAL.getSourceDeclExpression())
1184 return Visit(MakeCXCursor(E, StmtParent, TU));
1185 return false;
1186
1187 case TemplateArgument::Expression:
1188 if (Expr *E = TAL.getSourceExpression())
1189 return Visit(MakeCXCursor(E, StmtParent, TU));
1190 return false;
1191
1192 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001193 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1194 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001195 }
1196
1197 return false;
1198}
1199
Ted Kremeneka0536d82010-05-07 01:04:29 +00001200bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1201 return VisitDeclContext(D);
1202}
1203
Douglas Gregor01829d32010-08-31 14:41:23 +00001204bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1205 return Visit(TL.getUnqualifiedLoc());
1206}
1207
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001208bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1209 ASTContext &Context = TU->getASTContext();
1210
1211 // Some builtin types (such as Objective-C's "id", "sel", and
1212 // "Class") have associated declarations. Create cursors for those.
1213 QualType VisitType;
1214 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001215 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001216 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001217 case BuiltinType::Char_U:
1218 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001219 case BuiltinType::Char16:
1220 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001221 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001222 case BuiltinType::UInt:
1223 case BuiltinType::ULong:
1224 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001225 case BuiltinType::UInt128:
1226 case BuiltinType::Char_S:
1227 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001228 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001229 case BuiltinType::Short:
1230 case BuiltinType::Int:
1231 case BuiltinType::Long:
1232 case BuiltinType::LongLong:
1233 case BuiltinType::Int128:
1234 case BuiltinType::Float:
1235 case BuiltinType::Double:
1236 case BuiltinType::LongDouble:
1237 case BuiltinType::NullPtr:
1238 case BuiltinType::Overload:
1239 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001240 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001241
1242 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001243 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001244
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001245 case BuiltinType::ObjCId:
1246 VisitType = Context.getObjCIdType();
1247 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001248
1249 case BuiltinType::ObjCClass:
1250 VisitType = Context.getObjCClassType();
1251 break;
1252
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001253 case BuiltinType::ObjCSel:
1254 VisitType = Context.getObjCSelType();
1255 break;
1256 }
1257
1258 if (!VisitType.isNull()) {
1259 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001260 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001261 TU));
1262 }
1263
1264 return false;
1265}
1266
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001267bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1268 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1269}
1270
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001271bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1272 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1273}
1274
1275bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1276 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1277}
1278
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001279bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001280 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001281 // no context information with which we can match up the depth/index in the
1282 // type to the appropriate
1283 return false;
1284}
1285
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001286bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1287 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1288 return true;
1289
John McCallc12c5bb2010-05-15 11:32:37 +00001290 return false;
1291}
1292
1293bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1294 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1295 return true;
1296
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001297 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1298 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1299 TU)))
1300 return true;
1301 }
1302
1303 return false;
1304}
1305
1306bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001307 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001308}
1309
1310bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1311 return Visit(TL.getPointeeLoc());
1312}
1313
1314bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1315 return Visit(TL.getPointeeLoc());
1316}
1317
1318bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1319 return Visit(TL.getPointeeLoc());
1320}
1321
1322bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001323 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001324}
1325
1326bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001327 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001328}
1329
Douglas Gregor01829d32010-08-31 14:41:23 +00001330bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1331 bool SkipResultType) {
1332 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001333 return true;
1334
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001335 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001336 if (Decl *D = TL.getArg(I))
1337 if (Visit(MakeCXCursor(D, TU)))
1338 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001339
1340 return false;
1341}
1342
1343bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1344 if (Visit(TL.getElementLoc()))
1345 return true;
1346
1347 if (Expr *Size = TL.getSizeExpr())
1348 return Visit(MakeCXCursor(Size, StmtParent, TU));
1349
1350 return false;
1351}
1352
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001353bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1354 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001355 // Visit the template name.
1356 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1357 TL.getTemplateNameLoc()))
1358 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001359
1360 // Visit the template arguments.
1361 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1362 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1363 return true;
1364
1365 return false;
1366}
1367
Douglas Gregor2332c112010-01-21 20:48:56 +00001368bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1369 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1370}
1371
1372bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1373 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1374 return Visit(TSInfo->getTypeLoc());
1375
1376 return false;
1377}
1378
Douglas Gregora59e3902010-01-21 23:27:09 +00001379bool CursorVisitor::VisitStmt(Stmt *S) {
1380 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1381 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001382 if (Stmt *C = *Child)
1383 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1384 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001385 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001386
Douglas Gregora59e3902010-01-21 23:27:09 +00001387 return false;
1388}
1389
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001390bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1391 // Specially handle CaseStmts because they can be nested, e.g.:
1392 //
1393 // case 1:
1394 // case 2:
1395 //
1396 // In this case the second CaseStmt is the child of the first. Walking
1397 // these recursively can blow out the stack.
1398 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1399 while (true) {
1400 // Set the Parent field to Cursor, then back to its old value once we're
1401 // done.
1402 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1403
1404 if (Stmt *LHS = S->getLHS())
1405 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1406 return true;
1407 if (Stmt *RHS = S->getRHS())
1408 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1409 return true;
1410 if (Stmt *SubStmt = S->getSubStmt()) {
1411 if (!isa<CaseStmt>(SubStmt))
1412 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1413
1414 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1415 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1416 Cursor = MakeCXCursor(CS, StmtParent, TU);
1417 if (RegionOfInterest.isValid()) {
1418 SourceRange Range = CS->getSourceRange();
1419 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1420 return false;
1421 }
1422
1423 switch (Visitor(Cursor, Parent, ClientData)) {
1424 case CXChildVisit_Break: return true;
1425 case CXChildVisit_Continue: return false;
1426 case CXChildVisit_Recurse:
1427 // Perform tail-recursion manually.
1428 S = CS;
1429 continue;
1430 }
1431 }
1432 return false;
1433 }
1434}
1435
Douglas Gregora59e3902010-01-21 23:27:09 +00001436bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1437 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1438 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001439 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001440 return true;
1441 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001442
Douglas Gregora59e3902010-01-21 23:27:09 +00001443 return false;
1444}
1445
Douglas Gregor36897b02010-09-10 00:22:18 +00001446bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1447 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1448}
1449
Douglas Gregorf5bab412010-01-22 01:00:11 +00001450bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1451 if (VarDecl *Var = S->getConditionVariable()) {
1452 if (Visit(MakeCXCursor(Var, TU)))
1453 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001454 }
1455
Douglas Gregor263b47b2010-01-25 16:12:32 +00001456 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1457 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001458 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1459 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001460 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1461 return true;
1462
1463 return false;
1464}
1465
1466bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1467 if (VarDecl *Var = S->getConditionVariable()) {
1468 if (Visit(MakeCXCursor(Var, TU)))
1469 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001470 }
1471
Douglas Gregor263b47b2010-01-25 16:12:32 +00001472 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1473 return true;
1474 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1475 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001476
Douglas Gregor263b47b2010-01-25 16:12:32 +00001477 return false;
1478}
1479
1480bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1481 if (VarDecl *Var = S->getConditionVariable()) {
1482 if (Visit(MakeCXCursor(Var, TU)))
1483 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001484 }
1485
Douglas Gregor263b47b2010-01-25 16:12:32 +00001486 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1487 return true;
1488 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001489 return true;
1490
Douglas Gregor263b47b2010-01-25 16:12:32 +00001491 return false;
1492}
1493
1494bool CursorVisitor::VisitForStmt(ForStmt *S) {
1495 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1496 return true;
1497 if (VarDecl *Var = S->getConditionVariable()) {
1498 if (Visit(MakeCXCursor(Var, TU)))
1499 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001500 }
1501
Douglas Gregor263b47b2010-01-25 16:12:32 +00001502 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1503 return true;
1504 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1505 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001506 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1507 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001508
Douglas Gregorf5bab412010-01-22 01:00:11 +00001509 return false;
1510}
1511
Douglas Gregor8947a752010-09-02 20:35:02 +00001512bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1513 // Visit nested-name-specifier, if present.
1514 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1515 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1516 return true;
1517
1518 // Visit declaration name.
1519 if (VisitDeclarationNameInfo(E->getNameInfo()))
1520 return true;
1521
1522 // Visit explicitly-specified template arguments.
1523 if (E->hasExplicitTemplateArgs()) {
1524 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1525 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1526 *ArgEnd = Arg + Args.NumTemplateArgs;
1527 Arg != ArgEnd; ++Arg)
1528 if (VisitTemplateArgumentLoc(*Arg))
1529 return true;
1530 }
1531
1532 return false;
1533}
1534
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001535bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1536 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1537 return true;
1538
1539 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1540 return true;
1541
1542 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1543 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1544 return true;
1545
1546 return false;
1547}
1548
Ted Kremenek3064ef92010-08-27 21:34:58 +00001549bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1550 if (D->isDefinition()) {
1551 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1552 E = D->bases_end(); I != E; ++I) {
1553 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1554 return true;
1555 }
1556 }
1557
1558 return VisitTagDecl(D);
1559}
1560
1561
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001562bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1563 return Visit(B->getBlockDecl());
1564}
1565
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001566bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001567 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001568 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1569 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001570
1571 // Visit the components of the offsetof expression.
1572 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1573 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1574 const OffsetOfNode &Node = E->getComponent(I);
1575 switch (Node.getKind()) {
1576 case OffsetOfNode::Array:
1577 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1578 StmtParent, TU)))
1579 return true;
1580 break;
1581
1582 case OffsetOfNode::Field:
1583 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1584 TU)))
1585 return true;
1586 break;
1587
1588 case OffsetOfNode::Identifier:
1589 case OffsetOfNode::Base:
1590 continue;
1591 }
1592 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001593
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001594 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001595}
1596
Douglas Gregor336fd812010-01-23 00:40:08 +00001597bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1598 if (E->isArgumentType()) {
1599 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1600 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001601
Douglas Gregor336fd812010-01-23 00:40:08 +00001602 return false;
1603 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001604
Douglas Gregor336fd812010-01-23 00:40:08 +00001605 return VisitExpr(E);
1606}
1607
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001608bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1609 // Visit the base expression.
1610 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1611 return true;
1612
1613 // Visit the nested-name-specifier
1614 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1615 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1616 return true;
1617
1618 // Visit the declaration name.
1619 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1620 return true;
1621
1622 // Visit the explicitly-specified template arguments, if any.
1623 if (E->hasExplicitTemplateArgs()) {
1624 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1625 *ArgEnd = Arg + E->getNumTemplateArgs();
1626 Arg != ArgEnd;
1627 ++Arg) {
1628 if (VisitTemplateArgumentLoc(*Arg))
1629 return true;
1630 }
1631 }
1632
1633 return false;
1634}
1635
Douglas Gregor336fd812010-01-23 00:40:08 +00001636bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1637 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1638 if (Visit(TSInfo->getTypeLoc()))
1639 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001640
Douglas Gregor336fd812010-01-23 00:40:08 +00001641 return VisitCastExpr(E);
1642}
1643
1644bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1645 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1646 if (Visit(TSInfo->getTypeLoc()))
1647 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001648
Douglas Gregor336fd812010-01-23 00:40:08 +00001649 return VisitExpr(E);
1650}
1651
Douglas Gregor36897b02010-09-10 00:22:18 +00001652bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1653 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1654}
1655
Douglas Gregor648220e2010-08-10 15:02:34 +00001656bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1657 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1658 Visit(E->getArgTInfo2()->getTypeLoc());
1659}
1660
1661bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1662 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1663 return true;
1664
1665 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1666}
1667
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001668bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1669 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001670 if (InitListExpr *Syntactic = E->getSyntacticForm())
1671 return VisitExpr(Syntactic);
1672
1673 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001674}
1675
1676bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1677 // Visit the designators.
1678 typedef DesignatedInitExpr::Designator Designator;
1679 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1680 DEnd = E->designators_end();
1681 D != DEnd; ++D) {
1682 if (D->isFieldDesignator()) {
1683 if (FieldDecl *Field = D->getField())
1684 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1685 return true;
1686
1687 continue;
1688 }
1689
1690 if (D->isArrayDesignator()) {
1691 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1692 return true;
1693
1694 continue;
1695 }
1696
1697 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1698 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1699 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1700 return true;
1701 }
1702
1703 // Visit the initializer value itself.
1704 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1705}
1706
Douglas Gregor94802292010-09-02 21:20:16 +00001707bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1708 if (E->isTypeOperand()) {
1709 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1710 return Visit(TSInfo->getTypeLoc());
1711
1712 return false;
1713 }
1714
1715 return VisitExpr(E);
1716}
1717
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001718bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1719 if (E->isTypeOperand()) {
1720 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1721 return Visit(TSInfo->getTypeLoc());
1722
1723 return false;
1724 }
1725
1726 return VisitExpr(E);
1727}
1728
Douglas Gregorab6677e2010-09-08 00:15:04 +00001729bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1730 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1731 return Visit(TSInfo->getTypeLoc());
1732
1733 return VisitExpr(E);
1734}
1735
1736bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1737 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1738 return Visit(TSInfo->getTypeLoc());
1739
1740 return false;
1741}
1742
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001743bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1744 // Visit placement arguments.
1745 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1746 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1747 return true;
1748
1749 // Visit the allocated type.
1750 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1751 if (Visit(TSInfo->getTypeLoc()))
1752 return true;
1753
1754 // Visit the array size, if any.
1755 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1756 return true;
1757
1758 // Visit the initializer or constructor arguments.
1759 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1760 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1761 return true;
1762
1763 return false;
1764}
1765
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001766bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1767 // Visit base expression.
1768 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1769 return true;
1770
1771 // Visit the nested-name-specifier.
1772 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1773 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1774 return true;
1775
1776 // Visit the scope type that looks disturbingly like the nested-name-specifier
1777 // but isn't.
1778 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1779 if (Visit(TSInfo->getTypeLoc()))
1780 return true;
1781
1782 // Visit the name of the type being destroyed.
1783 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1784 if (Visit(TSInfo->getTypeLoc()))
1785 return true;
1786
1787 return false;
1788}
1789
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001790bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1791 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1792}
1793
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001794bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001795 // Visit the nested-name-specifier.
1796 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1797 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1798 return true;
1799
1800 // Visit the declaration name.
1801 if (VisitDeclarationNameInfo(E->getNameInfo()))
1802 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001803
1804 // Visit the overloaded declaration reference.
1805 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1806 return true;
1807
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001808 // Visit the explicitly-specified template arguments.
1809 if (const ExplicitTemplateArgumentList *ArgList
1810 = E->getOptionalExplicitTemplateArgs()) {
1811 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1812 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1813 Arg != ArgEnd; ++Arg) {
1814 if (VisitTemplateArgumentLoc(*Arg))
1815 return true;
1816 }
1817 }
1818
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001819 return false;
1820}
1821
Douglas Gregorbfebed22010-09-03 17:24:10 +00001822bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1823 DependentScopeDeclRefExpr *E) {
1824 // Visit the nested-name-specifier.
1825 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1826 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1827 return true;
1828
1829 // Visit the declaration name.
1830 if (VisitDeclarationNameInfo(E->getNameInfo()))
1831 return true;
1832
1833 // Visit the explicitly-specified template arguments.
1834 if (const ExplicitTemplateArgumentList *ArgList
1835 = E->getOptionalExplicitTemplateArgs()) {
1836 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1837 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1838 Arg != ArgEnd; ++Arg) {
1839 if (VisitTemplateArgumentLoc(*Arg))
1840 return true;
1841 }
1842 }
1843
1844 return false;
1845}
1846
Douglas Gregorab6677e2010-09-08 00:15:04 +00001847bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1848 CXXUnresolvedConstructExpr *E) {
1849 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1850 if (Visit(TSInfo->getTypeLoc()))
1851 return true;
1852
1853 return VisitExpr(E);
1854}
1855
Douglas Gregor25d63622010-09-03 17:35:34 +00001856bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1857 CXXDependentScopeMemberExpr *E) {
1858 // Visit the base expression, if there is one.
1859 if (!E->isImplicitAccess() &&
1860 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1861 return true;
1862
1863 // Visit the nested-name-specifier.
1864 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1865 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1866 return true;
1867
1868 // Visit the declaration name.
1869 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1870 return true;
1871
1872 // Visit the explicitly-specified template arguments.
1873 if (const ExplicitTemplateArgumentList *ArgList
1874 = E->getOptionalExplicitTemplateArgs()) {
1875 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1876 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1877 Arg != ArgEnd; ++Arg) {
1878 if (VisitTemplateArgumentLoc(*Arg))
1879 return true;
1880 }
1881 }
1882
1883 return false;
1884}
1885
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001886bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1887 // Visit the base expression, if there is one.
1888 if (!E->isImplicitAccess() &&
1889 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1890 return true;
1891
1892 return VisitOverloadExpr(E);
1893}
Douglas Gregor25d63622010-09-03 17:35:34 +00001894
Douglas Gregorc2350e52010-03-08 16:40:19 +00001895bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001896 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1897 if (Visit(TSInfo->getTypeLoc()))
1898 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001899
1900 return VisitExpr(E);
1901}
1902
Douglas Gregor81d34662010-04-20 15:39:42 +00001903bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1904 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1905}
1906
1907
Ted Kremenek09dfa372010-02-18 05:46:33 +00001908bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001909 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1910 i != e; ++i)
1911 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001912 return true;
1913
1914 return false;
1915}
1916
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001917static llvm::sys::Mutex EnableMultithreadingMutex;
1918static bool EnabledMultithreading;
1919
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001920extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001921CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1922 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00001923 // Disable pretty stack trace functionality, which will otherwise be a very
1924 // poor citizen of the world and set up all sorts of signal handlers.
1925 llvm::DisablePrettyStackTrace = true;
1926
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001927 // We use crash recovery to make some of our APIs more reliable, implicitly
1928 // enable it.
1929 llvm::CrashRecoveryContext::Enable();
1930
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001931 // Enable support for multithreading in LLVM.
1932 {
1933 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
1934 if (!EnabledMultithreading) {
1935 llvm::llvm_start_multithreaded();
1936 EnabledMultithreading = true;
1937 }
1938 }
1939
Douglas Gregora030b7c2010-01-22 20:35:53 +00001940 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001941 if (excludeDeclarationsFromPCH)
1942 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001943 if (displayDiagnostics)
1944 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001945 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001946}
1947
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001948void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001949 if (CIdx)
1950 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001951}
1952
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001953void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001954 if (CIdx) {
1955 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1956 CXXIdx->setUseExternalASTGeneration(value);
1957 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001958}
1959
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001960CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001961 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001962 if (!CIdx)
1963 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001964
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001965 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001966
Douglas Gregor28019772010-04-05 23:52:57 +00001967 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001968 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001969 CXXIdx->getOnlyLocalDecls(),
1970 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001971}
1972
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001973unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00001974 return CXTranslationUnit_PrecompiledPreamble |
1975 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001976}
1977
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001978CXTranslationUnit
1979clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1980 const char *source_filename,
1981 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001982 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001983 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001984 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001985 return clang_parseTranslationUnit(CIdx, source_filename,
1986 command_line_args, num_command_line_args,
1987 unsaved_files, num_unsaved_files,
1988 CXTranslationUnit_DetailedPreprocessingRecord);
1989}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001990
1991struct ParseTranslationUnitInfo {
1992 CXIndex CIdx;
1993 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001994 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001995 int num_command_line_args;
1996 struct CXUnsavedFile *unsaved_files;
1997 unsigned num_unsaved_files;
1998 unsigned options;
1999 CXTranslationUnit result;
2000};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002001static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002002 ParseTranslationUnitInfo *PTUI =
2003 static_cast<ParseTranslationUnitInfo*>(UserData);
2004 CXIndex CIdx = PTUI->CIdx;
2005 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002006 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002007 int num_command_line_args = PTUI->num_command_line_args;
2008 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2009 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2010 unsigned options = PTUI->options;
2011 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002012
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002013 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002014 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002015
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002016 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2017
Douglas Gregor44c181a2010-07-23 00:33:23 +00002018 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002019 bool CompleteTranslationUnit
2020 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002021 bool CacheCodeCompetionResults
2022 = options & CXTranslationUnit_CacheCompletionResults;
2023
Douglas Gregor5352ac02010-01-28 00:27:43 +00002024 // Configure the diagnostics.
2025 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002026 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2027 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002028
Douglas Gregor4db64a42010-01-23 00:14:00 +00002029 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2030 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002031 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002032 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002033 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002034 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2035 Buffer));
2036 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002037
Daniel Dunbar8506dde2009-12-03 01:54:28 +00002038 if (!CXXIdx->getUseExternalASTGeneration()) {
2039 llvm::SmallVector<const char *, 16> Args;
2040
2041 // The 'source_filename' argument is optional. If the caller does not
2042 // specify it then it is assumed that the source file is specified
2043 // in the actual argument list.
2044 if (source_filename)
2045 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002046
2047 // Since the Clang C library is primarily used by batch tools dealing with
2048 // (often very broken) source code, where spell-checking can have a
2049 // significant negative impact on performance (particularly when
2050 // precompiled headers are involved), we disable it by default.
Douglas Gregorfe08e402010-10-02 20:06:51 +00002051 // Only do this if we haven't found a spell-checking-related argument.
2052 bool FoundSpellCheckingArgument = false;
2053 for (int I = 0; I != num_command_line_args; ++I) {
2054 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2055 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2056 FoundSpellCheckingArgument = true;
2057 break;
2058 }
2059 }
2060 if (!FoundSpellCheckingArgument)
2061 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002062
Daniel Dunbar8506dde2009-12-03 01:54:28 +00002063 Args.insert(Args.end(), command_line_args,
2064 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00002065
Douglas Gregor44c181a2010-07-23 00:33:23 +00002066 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00002067 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2068 Args.push_back("-Xclang");
2069 Args.push_back("-detailed-preprocessing-record");
2070 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00002071
Douglas Gregor5352ac02010-01-28 00:27:43 +00002072 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002073
Ted Kremenek29b72842010-01-07 22:49:05 +00002074#ifdef USE_CRASHTRACER
2075 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00002076#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002077
Daniel Dunbar94220972009-12-05 02:17:18 +00002078 llvm::OwningPtr<ASTUnit> Unit(
2079 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00002080 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00002081 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00002082 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00002083 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00002084 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00002085 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00002086 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00002087 CompleteTranslationUnit,
2088 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002089
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002090 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00002091 // Make sure to check that 'Unit' is non-NULL.
2092 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00002093 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2094 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002095 D != DEnd; ++D) {
2096 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00002097 CXString Msg = clang_formatDiagnostic(&Diag,
2098 clang_defaultDiagnosticDisplayOptions());
2099 fprintf(stderr, "%s\n", clang_getCString(Msg));
2100 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002101 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002102#ifdef LLVM_ON_WIN32
2103 // On Windows, force a flush, since there may be multiple copies of
2104 // stderr and stdout in the file system, all with different buffers
2105 // but writing to the same device.
2106 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00002107#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002108 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002109 }
Daniel Dunbar94220972009-12-05 02:17:18 +00002110
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002111 PTUI->result = Unit.take();
2112 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00002113 }
2114
Ted Kremenek139ba862009-10-22 00:03:57 +00002115 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002116 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002117
Ted Kremenek139ba862009-10-22 00:03:57 +00002118 // First add the complete path to the 'clang' executable.
2119 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002120 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002121
Ted Kremenek139ba862009-10-22 00:03:57 +00002122 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002123 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002124
Ted Kremenek139ba862009-10-22 00:03:57 +00002125 // The 'source_filename' argument is optional. If the caller does not
2126 // specify it then it is assumed that the source file is specified
2127 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002128 if (source_filename)
2129 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00002130
Steve Naroff37b5ac22009-10-15 20:50:09 +00002131 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00002132 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00002133 char astTmpFile[L_tmpnam];
2134 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002135
2136 // Since the Clang C library is primarily used by batch tools dealing with
2137 // (often very broken) source code, where spell-checking can have a
2138 // significant negative impact on performance (particularly when
2139 // precompiled headers are involved), we disable it by default.
2140 // Note that we place this argument early in the list, so that it can be
2141 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00002142 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00002143
Douglas Gregor4db64a42010-01-23 00:14:00 +00002144 // Remap any unsaved files to temporary files.
2145 std::vector<llvm::sys::Path> TemporaryFiles;
2146 std::vector<std::string> RemapArgs;
2147 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002148 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002149
Douglas Gregor4db64a42010-01-23 00:14:00 +00002150 // The pointers into the elements of RemapArgs are stable because we
2151 // won't be adding anything to RemapArgs after this point.
2152 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
2153 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002154
Ted Kremenek139ba862009-10-22 00:03:57 +00002155 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
2156 for (int i = 0; i < num_command_line_args; ++i)
2157 if (const char *arg = command_line_args[i]) {
2158 if (strcmp(arg, "-o") == 0) {
2159 ++i; // Also skip the matching argument.
2160 continue;
2161 }
2162 if (strcmp(arg, "-emit-ast") == 0 ||
2163 strcmp(arg, "-c") == 0 ||
2164 strcmp(arg, "-fsyntax-only") == 0) {
2165 continue;
2166 }
2167
2168 // Keep the argument.
2169 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002170 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002171
Douglas Gregord93256e2010-01-28 06:00:51 +00002172 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00002173 char tmpFileResults[L_tmpnam];
2174 char *tmpResultsFileName = tmpnam(tmpFileResults);
2175 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00002176 TemporaryFiles.push_back(DiagnosticsFile);
2177 argv.push_back("-fdiagnostics-binary");
2178
Douglas Gregor44c181a2010-07-23 00:33:23 +00002179 // Do we need the detailed preprocessing record?
2180 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2181 argv.push_back("-Xclang");
2182 argv.push_back("-detailed-preprocessing-record");
2183 }
2184
Ted Kremenek139ba862009-10-22 00:03:57 +00002185 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002186 argv.push_back(NULL);
2187
Ted Kremenekfeb15e32009-10-26 22:14:08 +00002188 // Invoke 'clang'.
2189 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
2190 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00002191 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00002192 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
2193 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00002194 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002195 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00002196 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002197
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002198 if (!ErrMsg.empty()) {
2199 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00002200 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002201 I != E; ++I) {
2202 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00002203 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002204 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00002205 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002206
Daniel Dunbar32141c82010-02-23 20:23:45 +00002207 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00002208 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00002209
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002210 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002211 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00002212 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00002213 RemappedFiles.size(),
2214 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00002215 if (ATU) {
2216 LoadSerializedDiagnostics(DiagnosticsFile,
2217 num_unsaved_files, unsaved_files,
2218 ATU->getFileManager(),
2219 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00002220 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002221 } else if (CXXIdx->getDisplayDiagnostics()) {
2222 // We failed to load the ASTUnit, but we can still deserialize the
2223 // diagnostics and emit them.
2224 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00002225 Diagnostic Diag;
2226 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002227 // FIXME: Faked LangOpts!
2228 LangOptions LangOpts;
2229 llvm::SmallVector<StoredDiagnostic, 4> Diags;
2230 LoadSerializedDiagnostics(DiagnosticsFile,
2231 num_unsaved_files, unsaved_files,
2232 FileMgr, SourceMgr, Diags);
2233 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
2234 DEnd = Diags.end();
2235 D != DEnd; ++D) {
2236 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00002237 CXString Msg = clang_formatDiagnostic(&Diag,
2238 clang_defaultDiagnosticDisplayOptions());
2239 fprintf(stderr, "%s\n", clang_getCString(Msg));
2240 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002241 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002242
2243#ifdef LLVM_ON_WIN32
2244 // On Windows, force a flush, since there may be multiple copies of
2245 // stderr and stdout in the file system, all with different buffers
2246 // but writing to the same device.
2247 fflush(stderr);
2248#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00002249 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002250
Douglas Gregor313e26c2010-02-18 23:35:40 +00002251 if (ATU) {
2252 // Make the translation unit responsible for destroying all temporary files.
2253 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2254 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002255 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00002256 } else {
2257 // Destroy all of the temporary files now; they can't be referenced any
2258 // longer.
2259 llvm::sys::Path(astTmpFile).eraseFromDisk();
2260 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2261 TemporaryFiles[i].eraseFromDisk();
2262 }
2263
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002264 PTUI->result = ATU;
2265}
2266CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2267 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002268 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002269 int num_command_line_args,
2270 struct CXUnsavedFile *unsaved_files,
2271 unsigned num_unsaved_files,
2272 unsigned options) {
2273 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2274 num_command_line_args, unsaved_files, num_unsaved_files,
2275 options, 0 };
2276 llvm::CrashRecoveryContext CRC;
2277
2278 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002279 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2280 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2281 fprintf(stderr, " 'command_line_args' : [");
2282 for (int i = 0; i != num_command_line_args; ++i) {
2283 if (i)
2284 fprintf(stderr, ", ");
2285 fprintf(stderr, "'%s'", command_line_args[i]);
2286 }
2287 fprintf(stderr, "],\n");
2288 fprintf(stderr, " 'unsaved_files' : [");
2289 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2290 if (i)
2291 fprintf(stderr, ", ");
2292 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2293 unsaved_files[i].Length);
2294 }
2295 fprintf(stderr, "],\n");
2296 fprintf(stderr, " 'options' : %d,\n", options);
2297 fprintf(stderr, "}\n");
2298
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002299 return 0;
2300 }
2301
2302 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002303}
2304
Douglas Gregor19998442010-08-13 15:35:05 +00002305unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2306 return CXSaveTranslationUnit_None;
2307}
2308
2309int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2310 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002311 if (!TU)
2312 return 1;
2313
2314 return static_cast<ASTUnit *>(TU)->Save(FileName);
2315}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002316
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002317void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002318 if (CTUnit) {
2319 // If the translation unit has been marked as unsafe to free, just discard
2320 // it.
2321 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2322 return;
2323
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002324 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002325 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002326}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002327
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002328unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2329 return CXReparse_None;
2330}
2331
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002332struct ReparseTranslationUnitInfo {
2333 CXTranslationUnit TU;
2334 unsigned num_unsaved_files;
2335 struct CXUnsavedFile *unsaved_files;
2336 unsigned options;
2337 int result;
2338};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002339
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002340static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002341 ReparseTranslationUnitInfo *RTUI =
2342 static_cast<ReparseTranslationUnitInfo*>(UserData);
2343 CXTranslationUnit TU = RTUI->TU;
2344 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2345 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2346 unsigned options = RTUI->options;
2347 (void) options;
2348 RTUI->result = 1;
2349
Douglas Gregorabc563f2010-07-19 21:46:24 +00002350 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002351 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002352
2353 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2354 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002355
2356 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2357 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2358 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2359 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002360 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002361 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2362 Buffer));
2363 }
2364
Douglas Gregor593b0c12010-09-23 18:47:53 +00002365 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2366 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002367}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002368
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002369int clang_reparseTranslationUnit(CXTranslationUnit TU,
2370 unsigned num_unsaved_files,
2371 struct CXUnsavedFile *unsaved_files,
2372 unsigned options) {
2373 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2374 options, 0 };
2375 llvm::CrashRecoveryContext CRC;
2376
2377 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002378 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002379 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2380 return 1;
2381 }
2382
2383 return RTUI.result;
2384}
2385
Douglas Gregordf95a132010-08-09 20:45:32 +00002386
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002387CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002388 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002389 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002390
Steve Naroff77accc12009-09-03 18:19:54 +00002391 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002392 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002393}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002394
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002395CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002396 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002397 return Result;
2398}
2399
Ted Kremenekfb480492010-01-13 21:46:36 +00002400} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002401
Ted Kremenekfb480492010-01-13 21:46:36 +00002402//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002403// CXSourceLocation and CXSourceRange Operations.
2404//===----------------------------------------------------------------------===//
2405
Douglas Gregorb9790342010-01-22 21:44:22 +00002406extern "C" {
2407CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002408 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002409 return Result;
2410}
2411
2412unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002413 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2414 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2415 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002416}
2417
2418CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2419 CXFile file,
2420 unsigned line,
2421 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002422 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002423 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002424
Douglas Gregorb9790342010-01-22 21:44:22 +00002425 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2426 SourceLocation SLoc
2427 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002428 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002429 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002430
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002431 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002432}
2433
Douglas Gregor5352ac02010-01-28 00:27:43 +00002434CXSourceRange clang_getNullRange() {
2435 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2436 return Result;
2437}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002438
Douglas Gregor5352ac02010-01-28 00:27:43 +00002439CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2440 if (begin.ptr_data[0] != end.ptr_data[0] ||
2441 begin.ptr_data[1] != end.ptr_data[1])
2442 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002443
2444 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002445 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002446 return Result;
2447}
2448
Douglas Gregor46766dc2010-01-26 19:19:08 +00002449void clang_getInstantiationLocation(CXSourceLocation location,
2450 CXFile *file,
2451 unsigned *line,
2452 unsigned *column,
2453 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002454 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2455
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002456 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002457 if (file)
2458 *file = 0;
2459 if (line)
2460 *line = 0;
2461 if (column)
2462 *column = 0;
2463 if (offset)
2464 *offset = 0;
2465 return;
2466 }
2467
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002468 const SourceManager &SM =
2469 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002470 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002471
2472 if (file)
2473 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2474 if (line)
2475 *line = SM.getInstantiationLineNumber(InstLoc);
2476 if (column)
2477 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002478 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002479 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002480}
2481
Douglas Gregor1db19de2010-01-19 21:36:55 +00002482CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002483 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002484 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002485 return Result;
2486}
2487
2488CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002489 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002490 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002491 return Result;
2492}
2493
Douglas Gregorb9790342010-01-22 21:44:22 +00002494} // end: extern "C"
2495
Douglas Gregor1db19de2010-01-19 21:36:55 +00002496//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002497// CXFile Operations.
2498//===----------------------------------------------------------------------===//
2499
2500extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002501CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002502 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002503 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002504
Steve Naroff88145032009-10-27 14:35:18 +00002505 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002506 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002507}
2508
2509time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002510 if (!SFile)
2511 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002512
Steve Naroff88145032009-10-27 14:35:18 +00002513 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2514 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002515}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002516
Douglas Gregorb9790342010-01-22 21:44:22 +00002517CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2518 if (!tu)
2519 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002520
Douglas Gregorb9790342010-01-22 21:44:22 +00002521 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002522
Douglas Gregorb9790342010-01-22 21:44:22 +00002523 FileManager &FMgr = CXXUnit->getFileManager();
2524 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2525 return const_cast<FileEntry *>(File);
2526}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002527
Ted Kremenekfb480492010-01-13 21:46:36 +00002528} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002529
Ted Kremenekfb480492010-01-13 21:46:36 +00002530//===----------------------------------------------------------------------===//
2531// CXCursor Operations.
2532//===----------------------------------------------------------------------===//
2533
Ted Kremenekfb480492010-01-13 21:46:36 +00002534static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002535 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2536 return getDeclFromExpr(CE->getSubExpr());
2537
Ted Kremenekfb480492010-01-13 21:46:36 +00002538 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2539 return RefExpr->getDecl();
2540 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2541 return ME->getMemberDecl();
2542 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2543 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002544 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2545 return PRE->getProperty();
2546
Ted Kremenekfb480492010-01-13 21:46:36 +00002547 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2548 return getDeclFromExpr(CE->getCallee());
Ted Kremenekfb480492010-01-13 21:46:36 +00002549 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2550 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002551
Douglas Gregordb1314e2010-10-01 21:11:22 +00002552 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2553 return PE->getProtocol();
2554
Ted Kremenekfb480492010-01-13 21:46:36 +00002555 return 0;
2556}
2557
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002558static SourceLocation getLocationFromExpr(Expr *E) {
2559 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2560 return /*FIXME:*/Msg->getLeftLoc();
2561 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2562 return DRE->getLocation();
2563 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2564 return Member->getMemberLoc();
2565 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2566 return Ivar->getLocation();
2567 return E->getLocStart();
2568}
2569
Ted Kremenekfb480492010-01-13 21:46:36 +00002570extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002571
2572unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002573 CXCursorVisitor visitor,
2574 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002575 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002576
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002577 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2578 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002579 return CursorVis.VisitChildren(parent);
2580}
2581
Douglas Gregor78205d42010-01-20 21:45:58 +00002582static CXString getDeclSpelling(Decl *D) {
2583 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2584 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002585 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002586
Douglas Gregor78205d42010-01-20 21:45:58 +00002587 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002588 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002589
Douglas Gregor78205d42010-01-20 21:45:58 +00002590 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2591 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2592 // and returns different names. NamedDecl returns the class name and
2593 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002594 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002595
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002596 if (isa<UsingDirectiveDecl>(D))
2597 return createCXString("");
2598
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002599 llvm::SmallString<1024> S;
2600 llvm::raw_svector_ostream os(S);
2601 ND->printName(os);
2602
2603 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002604}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002605
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002606CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002607 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002608 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002609
Steve Narofff334b4e2009-09-02 18:26:48 +00002610 if (clang_isReference(C.kind)) {
2611 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002612 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002613 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002614 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002615 }
2616 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002617 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002618 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002619 }
2620 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002621 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002622 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002623 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002624 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002625 case CXCursor_CXXBaseSpecifier: {
2626 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2627 return createCXString(B->getType().getAsString());
2628 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002629 case CXCursor_TypeRef: {
2630 TypeDecl *Type = getCursorTypeRef(C).first;
2631 assert(Type && "Missing type decl");
2632
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002633 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2634 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002635 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002636 case CXCursor_TemplateRef: {
2637 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002638 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002639
2640 return createCXString(Template->getNameAsString());
2641 }
Douglas Gregor69319002010-08-31 23:48:11 +00002642
2643 case CXCursor_NamespaceRef: {
2644 NamedDecl *NS = getCursorNamespaceRef(C).first;
2645 assert(NS && "Missing namespace decl");
2646
2647 return createCXString(NS->getNameAsString());
2648 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002649
Douglas Gregora67e03f2010-09-09 21:42:20 +00002650 case CXCursor_MemberRef: {
2651 FieldDecl *Field = getCursorMemberRef(C).first;
2652 assert(Field && "Missing member decl");
2653
2654 return createCXString(Field->getNameAsString());
2655 }
2656
Douglas Gregor36897b02010-09-10 00:22:18 +00002657 case CXCursor_LabelRef: {
2658 LabelStmt *Label = getCursorLabelRef(C).first;
2659 assert(Label && "Missing label");
2660
2661 return createCXString(Label->getID()->getName());
2662 }
2663
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002664 case CXCursor_OverloadedDeclRef: {
2665 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2666 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2667 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2668 return createCXString(ND->getNameAsString());
2669 return createCXString("");
2670 }
2671 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2672 return createCXString(E->getName().getAsString());
2673 OverloadedTemplateStorage *Ovl
2674 = Storage.get<OverloadedTemplateStorage*>();
2675 if (Ovl->size() == 0)
2676 return createCXString("");
2677 return createCXString((*Ovl->begin())->getNameAsString());
2678 }
2679
Daniel Dunbaracca7252009-11-30 20:42:49 +00002680 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002681 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002682 }
2683 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002684
2685 if (clang_isExpression(C.kind)) {
2686 Decl *D = getDeclFromExpr(getCursorExpr(C));
2687 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002688 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002689 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002690 }
2691
Douglas Gregor36897b02010-09-10 00:22:18 +00002692 if (clang_isStatement(C.kind)) {
2693 Stmt *S = getCursorStmt(C);
2694 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2695 return createCXString(Label->getID()->getName());
2696
2697 return createCXString("");
2698 }
2699
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002700 if (C.kind == CXCursor_MacroInstantiation)
2701 return createCXString(getCursorMacroInstantiation(C)->getName()
2702 ->getNameStart());
2703
Douglas Gregor572feb22010-03-18 18:04:21 +00002704 if (C.kind == CXCursor_MacroDefinition)
2705 return createCXString(getCursorMacroDefinition(C)->getName()
2706 ->getNameStart());
2707
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002708 if (clang_isDeclaration(C.kind))
2709 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002710
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002711 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002712}
2713
Douglas Gregor358559d2010-10-02 22:49:11 +00002714CXString clang_getCursorDisplayName(CXCursor C) {
2715 if (!clang_isDeclaration(C.kind))
2716 return clang_getCursorSpelling(C);
2717
2718 Decl *D = getCursorDecl(C);
2719 if (!D)
2720 return createCXString("");
2721
2722 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2723 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2724 D = FunTmpl->getTemplatedDecl();
2725
2726 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2727 llvm::SmallString<64> Str;
2728 llvm::raw_svector_ostream OS(Str);
2729 OS << Function->getNameAsString();
2730 if (Function->getPrimaryTemplate())
2731 OS << "<>";
2732 OS << "(";
2733 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2734 if (I)
2735 OS << ", ";
2736 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2737 }
2738
2739 if (Function->isVariadic()) {
2740 if (Function->getNumParams())
2741 OS << ", ";
2742 OS << "...";
2743 }
2744 OS << ")";
2745 return createCXString(OS.str());
2746 }
2747
2748 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2749 llvm::SmallString<64> Str;
2750 llvm::raw_svector_ostream OS(Str);
2751 OS << ClassTemplate->getNameAsString();
2752 OS << "<";
2753 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2754 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2755 if (I)
2756 OS << ", ";
2757
2758 NamedDecl *Param = Params->getParam(I);
2759 if (Param->getIdentifier()) {
2760 OS << Param->getIdentifier()->getName();
2761 continue;
2762 }
2763
2764 // There is no parameter name, which makes this tricky. Try to come up
2765 // with something useful that isn't too long.
2766 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2767 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2768 else if (NonTypeTemplateParmDecl *NTTP
2769 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2770 OS << NTTP->getType().getAsString(Policy);
2771 else
2772 OS << "template<...> class";
2773 }
2774
2775 OS << ">";
2776 return createCXString(OS.str());
2777 }
2778
2779 if (ClassTemplateSpecializationDecl *ClassSpec
2780 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2781 // If the type was explicitly written, use that.
2782 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2783 return createCXString(TSInfo->getType().getAsString(Policy));
2784
2785 llvm::SmallString<64> Str;
2786 llvm::raw_svector_ostream OS(Str);
2787 OS << ClassSpec->getNameAsString();
2788 OS << TemplateSpecializationType::PrintTemplateArgumentList(
2789 ClassSpec->getTemplateArgs().getFlatArgumentList(),
2790 ClassSpec->getTemplateArgs().flat_size(),
2791 Policy);
2792 return createCXString(OS.str());
2793 }
2794
2795 return clang_getCursorSpelling(C);
2796}
2797
Ted Kremeneke68fff62010-02-17 00:41:32 +00002798CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002799 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002800 case CXCursor_FunctionDecl:
2801 return createCXString("FunctionDecl");
2802 case CXCursor_TypedefDecl:
2803 return createCXString("TypedefDecl");
2804 case CXCursor_EnumDecl:
2805 return createCXString("EnumDecl");
2806 case CXCursor_EnumConstantDecl:
2807 return createCXString("EnumConstantDecl");
2808 case CXCursor_StructDecl:
2809 return createCXString("StructDecl");
2810 case CXCursor_UnionDecl:
2811 return createCXString("UnionDecl");
2812 case CXCursor_ClassDecl:
2813 return createCXString("ClassDecl");
2814 case CXCursor_FieldDecl:
2815 return createCXString("FieldDecl");
2816 case CXCursor_VarDecl:
2817 return createCXString("VarDecl");
2818 case CXCursor_ParmDecl:
2819 return createCXString("ParmDecl");
2820 case CXCursor_ObjCInterfaceDecl:
2821 return createCXString("ObjCInterfaceDecl");
2822 case CXCursor_ObjCCategoryDecl:
2823 return createCXString("ObjCCategoryDecl");
2824 case CXCursor_ObjCProtocolDecl:
2825 return createCXString("ObjCProtocolDecl");
2826 case CXCursor_ObjCPropertyDecl:
2827 return createCXString("ObjCPropertyDecl");
2828 case CXCursor_ObjCIvarDecl:
2829 return createCXString("ObjCIvarDecl");
2830 case CXCursor_ObjCInstanceMethodDecl:
2831 return createCXString("ObjCInstanceMethodDecl");
2832 case CXCursor_ObjCClassMethodDecl:
2833 return createCXString("ObjCClassMethodDecl");
2834 case CXCursor_ObjCImplementationDecl:
2835 return createCXString("ObjCImplementationDecl");
2836 case CXCursor_ObjCCategoryImplDecl:
2837 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002838 case CXCursor_CXXMethod:
2839 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002840 case CXCursor_UnexposedDecl:
2841 return createCXString("UnexposedDecl");
2842 case CXCursor_ObjCSuperClassRef:
2843 return createCXString("ObjCSuperClassRef");
2844 case CXCursor_ObjCProtocolRef:
2845 return createCXString("ObjCProtocolRef");
2846 case CXCursor_ObjCClassRef:
2847 return createCXString("ObjCClassRef");
2848 case CXCursor_TypeRef:
2849 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002850 case CXCursor_TemplateRef:
2851 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002852 case CXCursor_NamespaceRef:
2853 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002854 case CXCursor_MemberRef:
2855 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002856 case CXCursor_LabelRef:
2857 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002858 case CXCursor_OverloadedDeclRef:
2859 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002860 case CXCursor_UnexposedExpr:
2861 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002862 case CXCursor_BlockExpr:
2863 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002864 case CXCursor_DeclRefExpr:
2865 return createCXString("DeclRefExpr");
2866 case CXCursor_MemberRefExpr:
2867 return createCXString("MemberRefExpr");
2868 case CXCursor_CallExpr:
2869 return createCXString("CallExpr");
2870 case CXCursor_ObjCMessageExpr:
2871 return createCXString("ObjCMessageExpr");
2872 case CXCursor_UnexposedStmt:
2873 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002874 case CXCursor_LabelStmt:
2875 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002876 case CXCursor_InvalidFile:
2877 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002878 case CXCursor_InvalidCode:
2879 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002880 case CXCursor_NoDeclFound:
2881 return createCXString("NoDeclFound");
2882 case CXCursor_NotImplemented:
2883 return createCXString("NotImplemented");
2884 case CXCursor_TranslationUnit:
2885 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002886 case CXCursor_UnexposedAttr:
2887 return createCXString("UnexposedAttr");
2888 case CXCursor_IBActionAttr:
2889 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002890 case CXCursor_IBOutletAttr:
2891 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002892 case CXCursor_IBOutletCollectionAttr:
2893 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002894 case CXCursor_PreprocessingDirective:
2895 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002896 case CXCursor_MacroDefinition:
2897 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002898 case CXCursor_MacroInstantiation:
2899 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002900 case CXCursor_Namespace:
2901 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002902 case CXCursor_LinkageSpec:
2903 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002904 case CXCursor_CXXBaseSpecifier:
2905 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002906 case CXCursor_Constructor:
2907 return createCXString("CXXConstructor");
2908 case CXCursor_Destructor:
2909 return createCXString("CXXDestructor");
2910 case CXCursor_ConversionFunction:
2911 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002912 case CXCursor_TemplateTypeParameter:
2913 return createCXString("TemplateTypeParameter");
2914 case CXCursor_NonTypeTemplateParameter:
2915 return createCXString("NonTypeTemplateParameter");
2916 case CXCursor_TemplateTemplateParameter:
2917 return createCXString("TemplateTemplateParameter");
2918 case CXCursor_FunctionTemplate:
2919 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002920 case CXCursor_ClassTemplate:
2921 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002922 case CXCursor_ClassTemplatePartialSpecialization:
2923 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002924 case CXCursor_NamespaceAlias:
2925 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002926 case CXCursor_UsingDirective:
2927 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002928 case CXCursor_UsingDeclaration:
2929 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002930 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002931
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002932 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002933 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002934}
Steve Naroff89922f82009-08-31 00:59:03 +00002935
Ted Kremeneke68fff62010-02-17 00:41:32 +00002936enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2937 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002938 CXClientData client_data) {
2939 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2940 *BestCursor = cursor;
2941 return CXChildVisit_Recurse;
2942}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002943
Douglas Gregorb9790342010-01-22 21:44:22 +00002944CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2945 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002946 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002947
Douglas Gregorb9790342010-01-22 21:44:22 +00002948 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002949 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2950
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002951 // Translate the given source location to make it point at the beginning of
2952 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002953 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002954
2955 // Guard against an invalid SourceLocation, or we may assert in one
2956 // of the following calls.
2957 if (SLoc.isInvalid())
2958 return clang_getNullCursor();
2959
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002960 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2961 CXXUnit->getASTContext().getLangOptions());
2962
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002963 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2964 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002965 // FIXME: Would be great to have a "hint" cursor, then walk from that
2966 // hint cursor upward until we find a cursor whose source range encloses
2967 // the region of interest, rather than starting from the translation unit.
2968 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002969 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002970 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002971 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002972 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002973 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002974}
2975
Ted Kremenek73885552009-11-17 19:28:59 +00002976CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002977 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002978}
2979
2980unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002981 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002982}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002983
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002984unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002985 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2986}
2987
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002988unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002989 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2990}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002991
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002992unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002993 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2994}
2995
Douglas Gregor97b98722010-01-19 23:20:36 +00002996unsigned clang_isExpression(enum CXCursorKind K) {
2997 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2998}
2999
3000unsigned clang_isStatement(enum CXCursorKind K) {
3001 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3002}
3003
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003004unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3005 return K == CXCursor_TranslationUnit;
3006}
3007
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003008unsigned clang_isPreprocessing(enum CXCursorKind K) {
3009 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3010}
3011
Ted Kremenekad6eff62010-03-08 21:17:29 +00003012unsigned clang_isUnexposed(enum CXCursorKind K) {
3013 switch (K) {
3014 case CXCursor_UnexposedDecl:
3015 case CXCursor_UnexposedExpr:
3016 case CXCursor_UnexposedStmt:
3017 case CXCursor_UnexposedAttr:
3018 return true;
3019 default:
3020 return false;
3021 }
3022}
3023
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003024CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003025 return C.kind;
3026}
3027
Douglas Gregor98258af2010-01-18 22:46:11 +00003028CXSourceLocation clang_getCursorLocation(CXCursor C) {
3029 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003030 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003031 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003032 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3033 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003034 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003035 }
3036
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003037 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003038 std::pair<ObjCProtocolDecl *, SourceLocation> P
3039 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003040 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003041 }
3042
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003043 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003044 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3045 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003046 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003047 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003048
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003049 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003050 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003051 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003052 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003053
3054 case CXCursor_TemplateRef: {
3055 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3056 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3057 }
3058
Douglas Gregor69319002010-08-31 23:48:11 +00003059 case CXCursor_NamespaceRef: {
3060 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3061 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3062 }
3063
Douglas Gregora67e03f2010-09-09 21:42:20 +00003064 case CXCursor_MemberRef: {
3065 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3066 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3067 }
3068
Ted Kremenek3064ef92010-08-27 21:34:58 +00003069 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003070 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3071 if (!BaseSpec)
3072 return clang_getNullLocation();
3073
3074 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3075 return cxloc::translateSourceLocation(getCursorContext(C),
3076 TSInfo->getTypeLoc().getBeginLoc());
3077
3078 return cxloc::translateSourceLocation(getCursorContext(C),
3079 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003080 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003081
Douglas Gregor36897b02010-09-10 00:22:18 +00003082 case CXCursor_LabelRef: {
3083 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3084 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3085 }
3086
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003087 case CXCursor_OverloadedDeclRef:
3088 return cxloc::translateSourceLocation(getCursorContext(C),
3089 getCursorOverloadedDeclRef(C).second);
3090
Douglas Gregorf46034a2010-01-18 23:41:10 +00003091 default:
3092 // FIXME: Need a way to enumerate all non-reference cases.
3093 llvm_unreachable("Missed a reference kind");
3094 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003095 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003096
3097 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003098 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003099 getLocationFromExpr(getCursorExpr(C)));
3100
Douglas Gregor36897b02010-09-10 00:22:18 +00003101 if (clang_isStatement(C.kind))
3102 return cxloc::translateSourceLocation(getCursorContext(C),
3103 getCursorStmt(C)->getLocStart());
3104
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003105 if (C.kind == CXCursor_PreprocessingDirective) {
3106 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3107 return cxloc::translateSourceLocation(getCursorContext(C), L);
3108 }
Douglas Gregor48072312010-03-18 15:23:44 +00003109
3110 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003111 SourceLocation L
3112 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003113 return cxloc::translateSourceLocation(getCursorContext(C), L);
3114 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003115
3116 if (C.kind == CXCursor_MacroDefinition) {
3117 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3118 return cxloc::translateSourceLocation(getCursorContext(C), L);
3119 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003120
Ted Kremenek9a700d22010-05-12 06:16:13 +00003121 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003122 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003123
Douglas Gregorf46034a2010-01-18 23:41:10 +00003124 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003125 SourceLocation Loc = D->getLocation();
3126 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3127 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003128 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003129}
Douglas Gregora7bde202010-01-19 00:34:46 +00003130
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003131} // end extern "C"
3132
3133static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003134 if (clang_isReference(C.kind)) {
3135 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003136 case CXCursor_ObjCSuperClassRef:
3137 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003138
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003139 case CXCursor_ObjCProtocolRef:
3140 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003141
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003142 case CXCursor_ObjCClassRef:
3143 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003144
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003145 case CXCursor_TypeRef:
3146 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003147
3148 case CXCursor_TemplateRef:
3149 return getCursorTemplateRef(C).second;
3150
Douglas Gregor69319002010-08-31 23:48:11 +00003151 case CXCursor_NamespaceRef:
3152 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003153
3154 case CXCursor_MemberRef:
3155 return getCursorMemberRef(C).second;
3156
Ted Kremenek3064ef92010-08-27 21:34:58 +00003157 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003158 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003159
Douglas Gregor36897b02010-09-10 00:22:18 +00003160 case CXCursor_LabelRef:
3161 return getCursorLabelRef(C).second;
3162
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003163 case CXCursor_OverloadedDeclRef:
3164 return getCursorOverloadedDeclRef(C).second;
3165
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003166 default:
3167 // FIXME: Need a way to enumerate all non-reference cases.
3168 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003169 }
3170 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003171
3172 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003173 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003174
3175 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003176 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003177
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003178 if (C.kind == CXCursor_PreprocessingDirective)
3179 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003180
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003181 if (C.kind == CXCursor_MacroInstantiation)
3182 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003183
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003184 if (C.kind == CXCursor_MacroDefinition)
3185 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003186
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003187 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
3188 return getCursorDecl(C)->getSourceRange();
3189
3190 return SourceRange();
3191}
3192
3193extern "C" {
3194
3195CXSourceRange clang_getCursorExtent(CXCursor C) {
3196 SourceRange R = getRawCursorExtent(C);
3197 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003198 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003199
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003200 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003201}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003202
3203CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003204 if (clang_isInvalid(C.kind))
3205 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003206
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003207 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003208 if (clang_isDeclaration(C.kind)) {
3209 Decl *D = getCursorDecl(C);
3210 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3211 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3212 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3213 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3214 if (ObjCForwardProtocolDecl *Protocols
3215 = dyn_cast<ObjCForwardProtocolDecl>(D))
3216 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3217
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003218 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003219 }
3220
Douglas Gregor97b98722010-01-19 23:20:36 +00003221 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003222 Expr *E = getCursorExpr(C);
3223 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003224 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003225 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003226
3227 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3228 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3229
Douglas Gregor97b98722010-01-19 23:20:36 +00003230 return clang_getNullCursor();
3231 }
3232
Douglas Gregor36897b02010-09-10 00:22:18 +00003233 if (clang_isStatement(C.kind)) {
3234 Stmt *S = getCursorStmt(C);
3235 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3236 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3237 getCursorASTUnit(C));
3238
3239 return clang_getNullCursor();
3240 }
3241
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003242 if (C.kind == CXCursor_MacroInstantiation) {
3243 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3244 return MakeMacroDefinitionCursor(Def, CXXUnit);
3245 }
3246
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003247 if (!clang_isReference(C.kind))
3248 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003249
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003250 switch (C.kind) {
3251 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003252 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003253
3254 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003255 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003256
3257 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003258 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003259
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003260 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003261 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003262
3263 case CXCursor_TemplateRef:
3264 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3265
Douglas Gregor69319002010-08-31 23:48:11 +00003266 case CXCursor_NamespaceRef:
3267 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3268
Douglas Gregora67e03f2010-09-09 21:42:20 +00003269 case CXCursor_MemberRef:
3270 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3271
Ted Kremenek3064ef92010-08-27 21:34:58 +00003272 case CXCursor_CXXBaseSpecifier: {
3273 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3274 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3275 CXXUnit));
3276 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003277
Douglas Gregor36897b02010-09-10 00:22:18 +00003278 case CXCursor_LabelRef:
3279 // FIXME: We end up faking the "parent" declaration here because we
3280 // don't want to make CXCursor larger.
3281 return MakeCXCursor(getCursorLabelRef(C).first,
3282 CXXUnit->getASTContext().getTranslationUnitDecl(),
3283 CXXUnit);
3284
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003285 case CXCursor_OverloadedDeclRef:
3286 return C;
3287
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003288 default:
3289 // We would prefer to enumerate all non-reference cursor kinds here.
3290 llvm_unreachable("Unhandled reference cursor kind");
3291 break;
3292 }
3293 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003294
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003295 return clang_getNullCursor();
3296}
3297
Douglas Gregorb6998662010-01-19 19:34:47 +00003298CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003299 if (clang_isInvalid(C.kind))
3300 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003301
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003302 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003303
Douglas Gregorb6998662010-01-19 19:34:47 +00003304 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003305 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003306 C = clang_getCursorReferenced(C);
3307 WasReference = true;
3308 }
3309
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003310 if (C.kind == CXCursor_MacroInstantiation)
3311 return clang_getCursorReferenced(C);
3312
Douglas Gregorb6998662010-01-19 19:34:47 +00003313 if (!clang_isDeclaration(C.kind))
3314 return clang_getNullCursor();
3315
3316 Decl *D = getCursorDecl(C);
3317 if (!D)
3318 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003319
Douglas Gregorb6998662010-01-19 19:34:47 +00003320 switch (D->getKind()) {
3321 // Declaration kinds that don't really separate the notions of
3322 // declaration and definition.
3323 case Decl::Namespace:
3324 case Decl::Typedef:
3325 case Decl::TemplateTypeParm:
3326 case Decl::EnumConstant:
3327 case Decl::Field:
3328 case Decl::ObjCIvar:
3329 case Decl::ObjCAtDefsField:
3330 case Decl::ImplicitParam:
3331 case Decl::ParmVar:
3332 case Decl::NonTypeTemplateParm:
3333 case Decl::TemplateTemplateParm:
3334 case Decl::ObjCCategoryImpl:
3335 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003336 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003337 case Decl::LinkageSpec:
3338 case Decl::ObjCPropertyImpl:
3339 case Decl::FileScopeAsm:
3340 case Decl::StaticAssert:
3341 case Decl::Block:
3342 return C;
3343
3344 // Declaration kinds that don't make any sense here, but are
3345 // nonetheless harmless.
3346 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003347 break;
3348
3349 // Declaration kinds for which the definition is not resolvable.
3350 case Decl::UnresolvedUsingTypename:
3351 case Decl::UnresolvedUsingValue:
3352 break;
3353
3354 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003355 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3356 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003357
3358 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003359 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003360
3361 case Decl::Enum:
3362 case Decl::Record:
3363 case Decl::CXXRecord:
3364 case Decl::ClassTemplateSpecialization:
3365 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003366 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003367 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003368 return clang_getNullCursor();
3369
3370 case Decl::Function:
3371 case Decl::CXXMethod:
3372 case Decl::CXXConstructor:
3373 case Decl::CXXDestructor:
3374 case Decl::CXXConversion: {
3375 const FunctionDecl *Def = 0;
3376 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003377 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003378 return clang_getNullCursor();
3379 }
3380
3381 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003382 // Ask the variable if it has a definition.
3383 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3384 return MakeCXCursor(Def, CXXUnit);
3385 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003386 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003387
Douglas Gregorb6998662010-01-19 19:34:47 +00003388 case Decl::FunctionTemplate: {
3389 const FunctionDecl *Def = 0;
3390 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003391 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003392 return clang_getNullCursor();
3393 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003394
Douglas Gregorb6998662010-01-19 19:34:47 +00003395 case Decl::ClassTemplate: {
3396 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003397 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003398 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003399 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003400 return clang_getNullCursor();
3401 }
3402
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003403 case Decl::Using:
3404 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3405 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003406
3407 case Decl::UsingShadow:
3408 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003409 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003410 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003411
3412 case Decl::ObjCMethod: {
3413 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3414 if (Method->isThisDeclarationADefinition())
3415 return C;
3416
3417 // Dig out the method definition in the associated
3418 // @implementation, if we have it.
3419 // FIXME: The ASTs should make finding the definition easier.
3420 if (ObjCInterfaceDecl *Class
3421 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3422 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3423 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3424 Method->isInstanceMethod()))
3425 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003426 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003427
3428 return clang_getNullCursor();
3429 }
3430
3431 case Decl::ObjCCategory:
3432 if (ObjCCategoryImplDecl *Impl
3433 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003434 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003435 return clang_getNullCursor();
3436
3437 case Decl::ObjCProtocol:
3438 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3439 return C;
3440 return clang_getNullCursor();
3441
3442 case Decl::ObjCInterface:
3443 // There are two notions of a "definition" for an Objective-C
3444 // class: the interface and its implementation. When we resolved a
3445 // reference to an Objective-C class, produce the @interface as
3446 // the definition; when we were provided with the interface,
3447 // produce the @implementation as the definition.
3448 if (WasReference) {
3449 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3450 return C;
3451 } else if (ObjCImplementationDecl *Impl
3452 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003453 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003454 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003455
Douglas Gregorb6998662010-01-19 19:34:47 +00003456 case Decl::ObjCProperty:
3457 // FIXME: We don't really know where to find the
3458 // ObjCPropertyImplDecls that implement this property.
3459 return clang_getNullCursor();
3460
3461 case Decl::ObjCCompatibleAlias:
3462 if (ObjCInterfaceDecl *Class
3463 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3464 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003465 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003466
Douglas Gregorb6998662010-01-19 19:34:47 +00003467 return clang_getNullCursor();
3468
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003469 case Decl::ObjCForwardProtocol:
3470 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3471 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003472
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003473 case Decl::ObjCClass:
3474 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3475 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003476
3477 case Decl::Friend:
3478 if (NamedDecl *Friend = cast<FriendDecl>(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 case Decl::FriendTemplate:
3483 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003484 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003485 return clang_getNullCursor();
3486 }
3487
3488 return clang_getNullCursor();
3489}
3490
3491unsigned clang_isCursorDefinition(CXCursor C) {
3492 if (!clang_isDeclaration(C.kind))
3493 return 0;
3494
3495 return clang_getCursorDefinition(C) == C;
3496}
3497
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003498unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003499 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003500 return 0;
3501
3502 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3503 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3504 return E->getNumDecls();
3505
3506 if (OverloadedTemplateStorage *S
3507 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3508 return S->size();
3509
3510 Decl *D = Storage.get<Decl*>();
3511 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3512 return Using->getNumShadowDecls();
3513 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3514 return Classes->size();
3515 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3516 return Protocols->protocol_size();
3517
3518 return 0;
3519}
3520
3521CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003522 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003523 return clang_getNullCursor();
3524
3525 if (index >= clang_getNumOverloadedDecls(cursor))
3526 return clang_getNullCursor();
3527
3528 ASTUnit *Unit = getCursorASTUnit(cursor);
3529 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3530 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3531 return MakeCXCursor(E->decls_begin()[index], Unit);
3532
3533 if (OverloadedTemplateStorage *S
3534 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3535 return MakeCXCursor(S->begin()[index], Unit);
3536
3537 Decl *D = Storage.get<Decl*>();
3538 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3539 // FIXME: This is, unfortunately, linear time.
3540 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3541 std::advance(Pos, index);
3542 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3543 }
3544
3545 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3546 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3547
3548 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3549 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3550
3551 return clang_getNullCursor();
3552}
3553
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003554void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003555 const char **startBuf,
3556 const char **endBuf,
3557 unsigned *startLine,
3558 unsigned *startColumn,
3559 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003560 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003561 assert(getCursorDecl(C) && "CXCursor has null decl");
3562 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003563 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3564 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003565
Steve Naroff4ade6d62009-09-23 17:52:52 +00003566 SourceManager &SM = FD->getASTContext().getSourceManager();
3567 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3568 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3569 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3570 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3571 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3572 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3573}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003574
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003575void clang_enableStackTraces(void) {
3576 llvm::sys::PrintStackTraceOnErrorSignal();
3577}
3578
Ted Kremenekfb480492010-01-13 21:46:36 +00003579} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003580
Ted Kremenekfb480492010-01-13 21:46:36 +00003581//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003582// Token-based Operations.
3583//===----------------------------------------------------------------------===//
3584
3585/* CXToken layout:
3586 * int_data[0]: a CXTokenKind
3587 * int_data[1]: starting token location
3588 * int_data[2]: token length
3589 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003590 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003591 * otherwise unused.
3592 */
3593extern "C" {
3594
3595CXTokenKind clang_getTokenKind(CXToken CXTok) {
3596 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3597}
3598
3599CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3600 switch (clang_getTokenKind(CXTok)) {
3601 case CXToken_Identifier:
3602 case CXToken_Keyword:
3603 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003604 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3605 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003606
3607 case CXToken_Literal: {
3608 // We have stashed the starting pointer in the ptr_data field. Use it.
3609 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003610 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003611 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003612
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003613 case CXToken_Punctuation:
3614 case CXToken_Comment:
3615 break;
3616 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003617
3618 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003619 // deconstructing the source location.
3620 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3621 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003622 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003623
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003624 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3625 std::pair<FileID, unsigned> LocInfo
3626 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003627 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003628 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003629 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3630 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003631 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003632
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003633 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003634}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003635
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003636CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3637 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3638 if (!CXXUnit)
3639 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003640
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003641 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3642 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3643}
3644
3645CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3646 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003647 if (!CXXUnit)
3648 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003649
3650 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003651 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3652}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003653
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003654void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3655 CXToken **Tokens, unsigned *NumTokens) {
3656 if (Tokens)
3657 *Tokens = 0;
3658 if (NumTokens)
3659 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003660
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003661 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3662 if (!CXXUnit || !Tokens || !NumTokens)
3663 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003664
Douglas Gregorbdf60622010-03-05 21:16:25 +00003665 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3666
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003667 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003668 if (R.isInvalid())
3669 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003670
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003671 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3672 std::pair<FileID, unsigned> BeginLocInfo
3673 = SourceMgr.getDecomposedLoc(R.getBegin());
3674 std::pair<FileID, unsigned> EndLocInfo
3675 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003676
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003677 // Cannot tokenize across files.
3678 if (BeginLocInfo.first != EndLocInfo.first)
3679 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003680
3681 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003682 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003683 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003684 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003685 if (Invalid)
3686 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003687
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003688 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3689 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003690 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003691 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003692
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003693 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003694 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003695 llvm::SmallVector<CXToken, 32> CXTokens;
3696 Token Tok;
3697 do {
3698 // Lex the next token
3699 Lex.LexFromRawLexer(Tok);
3700 if (Tok.is(tok::eof))
3701 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003702
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003703 // Initialize the CXToken.
3704 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003705
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003706 // - Common fields
3707 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3708 CXTok.int_data[2] = Tok.getLength();
3709 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003710
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003711 // - Kind-specific fields
3712 if (Tok.isLiteral()) {
3713 CXTok.int_data[0] = CXToken_Literal;
3714 CXTok.ptr_data = (void *)Tok.getLiteralData();
3715 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003716 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003717 std::pair<FileID, unsigned> LocInfo
3718 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003719 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003720 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003721 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3722 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003723 return;
3724
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003725 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003726 IdentifierInfo *II
3727 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003728
3729 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3730 CXTok.int_data[0] = CXToken_Keyword;
3731 }
3732 else {
3733 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3734 CXToken_Identifier
3735 : CXToken_Keyword;
3736 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003737 CXTok.ptr_data = II;
3738 } else if (Tok.is(tok::comment)) {
3739 CXTok.int_data[0] = CXToken_Comment;
3740 CXTok.ptr_data = 0;
3741 } else {
3742 CXTok.int_data[0] = CXToken_Punctuation;
3743 CXTok.ptr_data = 0;
3744 }
3745 CXTokens.push_back(CXTok);
3746 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003747
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003748 if (CXTokens.empty())
3749 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003750
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003751 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3752 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3753 *NumTokens = CXTokens.size();
3754}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003755
Ted Kremenek6db61092010-05-05 00:55:15 +00003756void clang_disposeTokens(CXTranslationUnit TU,
3757 CXToken *Tokens, unsigned NumTokens) {
3758 free(Tokens);
3759}
3760
3761} // end: extern "C"
3762
3763//===----------------------------------------------------------------------===//
3764// Token annotation APIs.
3765//===----------------------------------------------------------------------===//
3766
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003767typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003768static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3769 CXCursor parent,
3770 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003771namespace {
3772class AnnotateTokensWorker {
3773 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003774 CXToken *Tokens;
3775 CXCursor *Cursors;
3776 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003777 unsigned TokIdx;
3778 CursorVisitor AnnotateVis;
3779 SourceManager &SrcMgr;
3780
3781 bool MoreTokens() const { return TokIdx < NumTokens; }
3782 unsigned NextToken() const { return TokIdx; }
3783 void AdvanceToken() { ++TokIdx; }
3784 SourceLocation GetTokenLoc(unsigned tokI) {
3785 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3786 }
3787
Ted Kremenek6db61092010-05-05 00:55:15 +00003788public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003789 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003790 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3791 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003792 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003793 NumTokens(numTokens), TokIdx(0),
3794 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3795 Decl::MaxPCHLevel, RegionOfInterest),
3796 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003797
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003798 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003799 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003800 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003801};
3802}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003803
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003804void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3805 // Walk the AST within the region of interest, annotating tokens
3806 // along the way.
3807 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003808
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003809 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3810 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3811 if (Pos != Annotated.end())
3812 Cursors[I] = Pos->second;
3813 }
3814
3815 // Finish up annotating any tokens left.
3816 if (!MoreTokens())
3817 return;
3818
3819 const CXCursor &C = clang_getNullCursor();
3820 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3821 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3822 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003823 }
3824}
3825
Ted Kremenek6db61092010-05-05 00:55:15 +00003826enum CXChildVisitResult
3827AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003828 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3829 // We can always annotate a preprocessing directive/macro instantiation.
3830 if (clang_isPreprocessing(cursor.kind)) {
3831 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003832 return CXChildVisit_Recurse;
3833 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003834
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003835 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003836
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003837 if (cursorRange.isInvalid())
3838 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003839
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003840 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3841
Ted Kremeneka333c662010-05-12 05:29:33 +00003842 // Adjust the annotated range based specific declarations.
3843 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3844 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003845 Decl *D = cxcursor::getCursorDecl(cursor);
3846 // Don't visit synthesized ObjC methods, since they have no syntatic
3847 // representation in the source.
3848 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3849 if (MD->isSynthesized())
3850 return CXChildVisit_Continue;
3851 }
3852 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003853 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3854 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003855 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003856 if (TLoc.isValid() &&
3857 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003858 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003859 }
3860 }
3861 }
3862
Ted Kremenek3f404602010-08-14 01:14:06 +00003863 // If the location of the cursor occurs within a macro instantiation, record
3864 // the spelling location of the cursor in our annotation map. We can then
3865 // paper over the token labelings during a post-processing step to try and
3866 // get cursor mappings for tokens that are the *arguments* of a macro
3867 // instantiation.
3868 if (L.isMacroID()) {
3869 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3870 // Only invalidate the old annotation if it isn't part of a preprocessing
3871 // directive. Here we assume that the default construction of CXCursor
3872 // results in CXCursor.kind being an initialized value (i.e., 0). If
3873 // this isn't the case, we can fix by doing lookup + insertion.
3874
3875 CXCursor &oldC = Annotated[rawEncoding];
3876 if (!clang_isPreprocessing(oldC.kind))
3877 oldC = cursor;
3878 }
3879
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003880 const enum CXCursorKind K = clang_getCursorKind(parent);
3881 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003882 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3883 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003884
3885 while (MoreTokens()) {
3886 const unsigned I = NextToken();
3887 SourceLocation TokLoc = GetTokenLoc(I);
3888 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3889 case RangeBefore:
3890 Cursors[I] = updateC;
3891 AdvanceToken();
3892 continue;
3893 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003894 case RangeOverlap:
3895 break;
3896 }
3897 break;
3898 }
3899
3900 // Visit children to get their cursor information.
3901 const unsigned BeforeChildren = NextToken();
3902 VisitChildren(cursor);
3903 const unsigned AfterChildren = NextToken();
3904
3905 // Adjust 'Last' to the last token within the extent of the cursor.
3906 while (MoreTokens()) {
3907 const unsigned I = NextToken();
3908 SourceLocation TokLoc = GetTokenLoc(I);
3909 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3910 case RangeBefore:
3911 assert(0 && "Infeasible");
3912 case RangeAfter:
3913 break;
3914 case RangeOverlap:
3915 Cursors[I] = updateC;
3916 AdvanceToken();
3917 continue;
3918 }
3919 break;
3920 }
3921 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003922
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003923 // Scan the tokens that are at the beginning of the cursor, but are not
3924 // capture by the child cursors.
3925
3926 // For AST elements within macros, rely on a post-annotate pass to
3927 // to correctly annotate the tokens with cursors. Otherwise we can
3928 // get confusing results of having tokens that map to cursors that really
3929 // are expanded by an instantiation.
3930 if (L.isMacroID())
3931 cursor = clang_getNullCursor();
3932
3933 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3934 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3935 break;
3936 Cursors[I] = cursor;
3937 }
3938 // Scan the tokens that are at the end of the cursor, but are not captured
3939 // but the child cursors.
3940 for (unsigned I = AfterChildren; I != Last; ++I)
3941 Cursors[I] = cursor;
3942
3943 TokIdx = Last;
3944 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003945}
3946
Ted Kremenek6db61092010-05-05 00:55:15 +00003947static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3948 CXCursor parent,
3949 CXClientData client_data) {
3950 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3951}
3952
3953extern "C" {
3954
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003955void clang_annotateTokens(CXTranslationUnit TU,
3956 CXToken *Tokens, unsigned NumTokens,
3957 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003958
3959 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003960 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003961
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003962 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003963 if (!CXXUnit) {
3964 // Any token we don't specifically annotate will have a NULL cursor.
3965 const CXCursor &C = clang_getNullCursor();
3966 for (unsigned I = 0; I != NumTokens; ++I)
3967 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003968 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003969 }
3970
Douglas Gregorbdf60622010-03-05 21:16:25 +00003971 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003972
Douglas Gregor0396f462010-03-19 05:22:59 +00003973 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003974 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003975 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3976 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003977 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3978 clang_getTokenLocation(TU,
3979 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003980
Douglas Gregor0396f462010-03-19 05:22:59 +00003981 // A mapping from the source locations found when re-lexing or traversing the
3982 // region of interest to the corresponding cursors.
3983 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003984
3985 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003986 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003987 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3988 std::pair<FileID, unsigned> BeginLocInfo
3989 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3990 std::pair<FileID, unsigned> EndLocInfo
3991 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003992
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003993 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003994 bool Invalid = false;
3995 if (BeginLocInfo.first == EndLocInfo.first &&
3996 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3997 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003998 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3999 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004000 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004001 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004002 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004003
4004 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004005 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004006 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004007 Token Tok;
4008 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004009
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004010 reprocess:
4011 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4012 // We have found a preprocessing directive. Gobble it up so that we
4013 // don't see it while preprocessing these tokens later, but keep track of
4014 // all of the token locations inside this preprocessing directive so that
4015 // we can annotate them appropriately.
4016 //
4017 // FIXME: Some simple tests here could identify macro definitions and
4018 // #undefs, to provide specific cursor kinds for those.
4019 std::vector<SourceLocation> Locations;
4020 do {
4021 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004022 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004023 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004024
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004025 using namespace cxcursor;
4026 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004027 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4028 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004029 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004030 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4031 Annotated[Locations[I].getRawEncoding()] = Cursor;
4032 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004033
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004034 if (Tok.isAtStartOfLine())
4035 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004036
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004037 continue;
4038 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004039
Douglas Gregor48072312010-03-18 15:23:44 +00004040 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004041 break;
4042 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004043 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004044
Douglas Gregor0396f462010-03-19 05:22:59 +00004045 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004046 // a specific cursor.
4047 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4048 CXXUnit, RegionOfInterest);
4049 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004050}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004051} // end: extern "C"
4052
4053//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004054// Operations for querying linkage of a cursor.
4055//===----------------------------------------------------------------------===//
4056
4057extern "C" {
4058CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004059 if (!clang_isDeclaration(cursor.kind))
4060 return CXLinkage_Invalid;
4061
Ted Kremenek16b42592010-03-03 06:36:57 +00004062 Decl *D = cxcursor::getCursorDecl(cursor);
4063 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4064 switch (ND->getLinkage()) {
4065 case NoLinkage: return CXLinkage_NoLinkage;
4066 case InternalLinkage: return CXLinkage_Internal;
4067 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4068 case ExternalLinkage: return CXLinkage_External;
4069 };
4070
4071 return CXLinkage_Invalid;
4072}
4073} // end: extern "C"
4074
4075//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004076// Operations for querying language of a cursor.
4077//===----------------------------------------------------------------------===//
4078
4079static CXLanguageKind getDeclLanguage(const Decl *D) {
4080 switch (D->getKind()) {
4081 default:
4082 break;
4083 case Decl::ImplicitParam:
4084 case Decl::ObjCAtDefsField:
4085 case Decl::ObjCCategory:
4086 case Decl::ObjCCategoryImpl:
4087 case Decl::ObjCClass:
4088 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004089 case Decl::ObjCForwardProtocol:
4090 case Decl::ObjCImplementation:
4091 case Decl::ObjCInterface:
4092 case Decl::ObjCIvar:
4093 case Decl::ObjCMethod:
4094 case Decl::ObjCProperty:
4095 case Decl::ObjCPropertyImpl:
4096 case Decl::ObjCProtocol:
4097 return CXLanguage_ObjC;
4098 case Decl::CXXConstructor:
4099 case Decl::CXXConversion:
4100 case Decl::CXXDestructor:
4101 case Decl::CXXMethod:
4102 case Decl::CXXRecord:
4103 case Decl::ClassTemplate:
4104 case Decl::ClassTemplatePartialSpecialization:
4105 case Decl::ClassTemplateSpecialization:
4106 case Decl::Friend:
4107 case Decl::FriendTemplate:
4108 case Decl::FunctionTemplate:
4109 case Decl::LinkageSpec:
4110 case Decl::Namespace:
4111 case Decl::NamespaceAlias:
4112 case Decl::NonTypeTemplateParm:
4113 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004114 case Decl::TemplateTemplateParm:
4115 case Decl::TemplateTypeParm:
4116 case Decl::UnresolvedUsingTypename:
4117 case Decl::UnresolvedUsingValue:
4118 case Decl::Using:
4119 case Decl::UsingDirective:
4120 case Decl::UsingShadow:
4121 return CXLanguage_CPlusPlus;
4122 }
4123
4124 return CXLanguage_C;
4125}
4126
4127extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004128
4129enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4130 if (clang_isDeclaration(cursor.kind))
4131 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4132 if (D->hasAttr<UnavailableAttr>() ||
4133 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4134 return CXAvailability_Available;
4135
4136 if (D->hasAttr<DeprecatedAttr>())
4137 return CXAvailability_Deprecated;
4138 }
4139
4140 return CXAvailability_Available;
4141}
4142
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004143CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4144 if (clang_isDeclaration(cursor.kind))
4145 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4146
4147 return CXLanguage_Invalid;
4148}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004149
4150CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4151 if (clang_isDeclaration(cursor.kind)) {
4152 if (Decl *D = getCursorDecl(cursor)) {
4153 DeclContext *DC = D->getDeclContext();
4154 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4155 }
4156 }
4157
4158 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4159 if (Decl *D = getCursorDecl(cursor))
4160 return MakeCXCursor(D, getCursorASTUnit(cursor));
4161 }
4162
4163 return clang_getNullCursor();
4164}
4165
4166CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4167 if (clang_isDeclaration(cursor.kind)) {
4168 if (Decl *D = getCursorDecl(cursor)) {
4169 DeclContext *DC = D->getLexicalDeclContext();
4170 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4171 }
4172 }
4173
4174 // FIXME: Note that we can't easily compute the lexical context of a
4175 // statement or expression, so we return nothing.
4176 return clang_getNullCursor();
4177}
4178
Douglas Gregor9f592342010-10-01 20:25:15 +00004179static void CollectOverriddenMethods(DeclContext *Ctx,
4180 ObjCMethodDecl *Method,
4181 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4182 if (!Ctx)
4183 return;
4184
4185 // If we have a class or category implementation, jump straight to the
4186 // interface.
4187 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4188 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4189
4190 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4191 if (!Container)
4192 return;
4193
4194 // Check whether we have a matching method at this level.
4195 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4196 Method->isInstanceMethod()))
4197 if (Method != Overridden) {
4198 // We found an override at this level; there is no need to look
4199 // into other protocols or categories.
4200 Methods.push_back(Overridden);
4201 return;
4202 }
4203
4204 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4205 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4206 PEnd = Protocol->protocol_end();
4207 P != PEnd; ++P)
4208 CollectOverriddenMethods(*P, Method, Methods);
4209 }
4210
4211 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4212 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4213 PEnd = Category->protocol_end();
4214 P != PEnd; ++P)
4215 CollectOverriddenMethods(*P, Method, Methods);
4216 }
4217
4218 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4219 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4220 PEnd = Interface->protocol_end();
4221 P != PEnd; ++P)
4222 CollectOverriddenMethods(*P, Method, Methods);
4223
4224 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4225 Category; Category = Category->getNextClassCategory())
4226 CollectOverriddenMethods(Category, Method, Methods);
4227
4228 // We only look into the superclass if we haven't found anything yet.
4229 if (Methods.empty())
4230 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4231 return CollectOverriddenMethods(Super, Method, Methods);
4232 }
4233}
4234
4235void clang_getOverriddenCursors(CXCursor cursor,
4236 CXCursor **overridden,
4237 unsigned *num_overridden) {
4238 if (overridden)
4239 *overridden = 0;
4240 if (num_overridden)
4241 *num_overridden = 0;
4242 if (!overridden || !num_overridden)
4243 return;
4244
4245 if (!clang_isDeclaration(cursor.kind))
4246 return;
4247
4248 Decl *D = getCursorDecl(cursor);
4249 if (!D)
4250 return;
4251
4252 // Handle C++ member functions.
4253 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4254 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4255 *num_overridden = CXXMethod->size_overridden_methods();
4256 if (!*num_overridden)
4257 return;
4258
4259 *overridden = new CXCursor [*num_overridden];
4260 unsigned I = 0;
4261 for (CXXMethodDecl::method_iterator
4262 M = CXXMethod->begin_overridden_methods(),
4263 MEnd = CXXMethod->end_overridden_methods();
4264 M != MEnd; (void)++M, ++I)
4265 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4266 return;
4267 }
4268
4269 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4270 if (!Method)
4271 return;
4272
4273 // Handle Objective-C methods.
4274 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4275 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4276
4277 if (Methods.empty())
4278 return;
4279
4280 *num_overridden = Methods.size();
4281 *overridden = new CXCursor [Methods.size()];
4282 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4283 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4284}
4285
4286void clang_disposeOverriddenCursors(CXCursor *overridden) {
4287 delete [] overridden;
4288}
4289
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004290} // end: extern "C"
4291
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004292
4293//===----------------------------------------------------------------------===//
4294// C++ AST instrospection.
4295//===----------------------------------------------------------------------===//
4296
4297extern "C" {
4298unsigned clang_CXXMethod_isStatic(CXCursor C) {
4299 if (!clang_isDeclaration(C.kind))
4300 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004301
4302 CXXMethodDecl *Method = 0;
4303 Decl *D = cxcursor::getCursorDecl(C);
4304 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4305 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4306 else
4307 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4308 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004309}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004310
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004311} // end: extern "C"
4312
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004313//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004314// Attribute introspection.
4315//===----------------------------------------------------------------------===//
4316
4317extern "C" {
4318CXType clang_getIBOutletCollectionType(CXCursor C) {
4319 if (C.kind != CXCursor_IBOutletCollectionAttr)
4320 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4321
4322 IBOutletCollectionAttr *A =
4323 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4324
4325 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4326}
4327} // end: extern "C"
4328
4329//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004330// CXString Operations.
4331//===----------------------------------------------------------------------===//
4332
4333extern "C" {
4334const char *clang_getCString(CXString string) {
4335 return string.Spelling;
4336}
4337
4338void clang_disposeString(CXString string) {
4339 if (string.MustFreeString && string.Spelling)
4340 free((void*)string.Spelling);
4341}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004342
Ted Kremenekfb480492010-01-13 21:46:36 +00004343} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004344
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004345namespace clang { namespace cxstring {
4346CXString createCXString(const char *String, bool DupString){
4347 CXString Str;
4348 if (DupString) {
4349 Str.Spelling = strdup(String);
4350 Str.MustFreeString = 1;
4351 } else {
4352 Str.Spelling = String;
4353 Str.MustFreeString = 0;
4354 }
4355 return Str;
4356}
4357
4358CXString createCXString(llvm::StringRef String, bool DupString) {
4359 CXString Result;
4360 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4361 char *Spelling = (char *)malloc(String.size() + 1);
4362 memmove(Spelling, String.data(), String.size());
4363 Spelling[String.size()] = 0;
4364 Result.Spelling = Spelling;
4365 Result.MustFreeString = 1;
4366 } else {
4367 Result.Spelling = String.data();
4368 Result.MustFreeString = 0;
4369 }
4370 return Result;
4371}
4372}}
4373
Ted Kremenek04bb7162010-01-22 22:44:15 +00004374//===----------------------------------------------------------------------===//
4375// Misc. utility functions.
4376//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004377
Ted Kremenek04bb7162010-01-22 22:44:15 +00004378extern "C" {
4379
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004380CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004381 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004382}
4383
4384} // end: extern "C"