blob: a5b342dbe75f4e80c43badf84998dbbf5045e2c7 [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 Dunbar9ebfa312009-12-01 03:14:51 +00001953CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001954 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001955 if (!CIdx)
1956 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001957
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001958 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001959
Douglas Gregor28019772010-04-05 23:52:57 +00001960 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001961 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001962 CXXIdx->getOnlyLocalDecls(),
1963 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001964}
1965
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001966unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00001967 return CXTranslationUnit_PrecompiledPreamble |
1968 CXTranslationUnit_CacheCompletionResults;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001969}
1970
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001971CXTranslationUnit
1972clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1973 const char *source_filename,
1974 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001975 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001976 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001977 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001978 return clang_parseTranslationUnit(CIdx, source_filename,
1979 command_line_args, num_command_line_args,
1980 unsaved_files, num_unsaved_files,
1981 CXTranslationUnit_DetailedPreprocessingRecord);
1982}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001983
1984struct ParseTranslationUnitInfo {
1985 CXIndex CIdx;
1986 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001987 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001988 int num_command_line_args;
1989 struct CXUnsavedFile *unsaved_files;
1990 unsigned num_unsaved_files;
1991 unsigned options;
1992 CXTranslationUnit result;
1993};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001994static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001995 ParseTranslationUnitInfo *PTUI =
1996 static_cast<ParseTranslationUnitInfo*>(UserData);
1997 CXIndex CIdx = PTUI->CIdx;
1998 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001999 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002000 int num_command_line_args = PTUI->num_command_line_args;
2001 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2002 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2003 unsigned options = PTUI->options;
2004 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002005
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002006 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002007 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002008
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002009 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2010
Douglas Gregor44c181a2010-07-23 00:33:23 +00002011 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002012 bool CompleteTranslationUnit
2013 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002014 bool CacheCodeCompetionResults
2015 = options & CXTranslationUnit_CacheCompletionResults;
2016
Douglas Gregor5352ac02010-01-28 00:27:43 +00002017 // Configure the diagnostics.
2018 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002019 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2020 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002021
Douglas Gregor4db64a42010-01-23 00:14:00 +00002022 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2023 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002024 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002025 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002026 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002027 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2028 Buffer));
2029 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002030
Douglas Gregorb10daed2010-10-11 16:52:23 +00002031 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002032
Ted Kremenek139ba862009-10-22 00:03:57 +00002033 // The 'source_filename' argument is optional. If the caller does not
2034 // specify it then it is assumed that the source file is specified
2035 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002036 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002037 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002038
2039 // Since the Clang C library is primarily used by batch tools dealing with
2040 // (often very broken) source code, where spell-checking can have a
2041 // significant negative impact on performance (particularly when
2042 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002043 // Only do this if we haven't found a spell-checking-related argument.
2044 bool FoundSpellCheckingArgument = false;
2045 for (int I = 0; I != num_command_line_args; ++I) {
2046 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2047 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2048 FoundSpellCheckingArgument = true;
2049 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002050 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002051 }
2052 if (!FoundSpellCheckingArgument)
2053 Args.push_back("-fno-spell-checking");
2054
2055 Args.insert(Args.end(), command_line_args,
2056 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002057
Douglas Gregor44c181a2010-07-23 00:33:23 +00002058 // Do we need the detailed preprocessing record?
2059 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002060 Args.push_back("-Xclang");
2061 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002062 }
2063
Douglas Gregorb10daed2010-10-11 16:52:23 +00002064 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenek74cd0692009-10-15 23:21:22 +00002065
Douglas Gregorb10daed2010-10-11 16:52:23 +00002066#ifdef USE_CRASHTRACER
2067 ArgsCrashTracerInfo ACTI(Args);
2068#endif
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002069
Douglas Gregorb10daed2010-10-11 16:52:23 +00002070 llvm::OwningPtr<ASTUnit> Unit(
2071 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2072 Diags,
2073 CXXIdx->getClangResourcesPath(),
2074 CXXIdx->getOnlyLocalDecls(),
2075 RemappedFiles.data(),
2076 RemappedFiles.size(),
2077 /*CaptureDiagnostics=*/true,
2078 PrecompilePreamble,
2079 CompleteTranslationUnit,
2080 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002081
Douglas Gregorb10daed2010-10-11 16:52:23 +00002082 if (NumErrors != Diags->getNumErrors()) {
2083 // Make sure to check that 'Unit' is non-NULL.
2084 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2085 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2086 DEnd = Unit->stored_diag_end();
2087 D != DEnd; ++D) {
2088 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2089 CXString Msg = clang_formatDiagnostic(&Diag,
2090 clang_defaultDiagnosticDisplayOptions());
2091 fprintf(stderr, "%s\n", clang_getCString(Msg));
2092 clang_disposeString(Msg);
2093 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002094#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002095 // On Windows, force a flush, since there may be multiple copies of
2096 // stderr and stdout in the file system, all with different buffers
2097 // but writing to the same device.
2098 fflush(stderr);
2099#endif
2100 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002101 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002102
Douglas Gregorb10daed2010-10-11 16:52:23 +00002103 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002104}
2105CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2106 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002107 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002108 int num_command_line_args,
2109 struct CXUnsavedFile *unsaved_files,
2110 unsigned num_unsaved_files,
2111 unsigned options) {
2112 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2113 num_command_line_args, unsaved_files, num_unsaved_files,
2114 options, 0 };
2115 llvm::CrashRecoveryContext CRC;
2116
2117 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002118 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2119 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2120 fprintf(stderr, " 'command_line_args' : [");
2121 for (int i = 0; i != num_command_line_args; ++i) {
2122 if (i)
2123 fprintf(stderr, ", ");
2124 fprintf(stderr, "'%s'", command_line_args[i]);
2125 }
2126 fprintf(stderr, "],\n");
2127 fprintf(stderr, " 'unsaved_files' : [");
2128 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2129 if (i)
2130 fprintf(stderr, ", ");
2131 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2132 unsaved_files[i].Length);
2133 }
2134 fprintf(stderr, "],\n");
2135 fprintf(stderr, " 'options' : %d,\n", options);
2136 fprintf(stderr, "}\n");
2137
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002138 return 0;
2139 }
2140
2141 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002142}
2143
Douglas Gregor19998442010-08-13 15:35:05 +00002144unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2145 return CXSaveTranslationUnit_None;
2146}
2147
2148int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2149 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002150 if (!TU)
2151 return 1;
2152
2153 return static_cast<ASTUnit *>(TU)->Save(FileName);
2154}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002155
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002156void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002157 if (CTUnit) {
2158 // If the translation unit has been marked as unsafe to free, just discard
2159 // it.
2160 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2161 return;
2162
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002163 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002164 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002165}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002166
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002167unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2168 return CXReparse_None;
2169}
2170
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002171struct ReparseTranslationUnitInfo {
2172 CXTranslationUnit TU;
2173 unsigned num_unsaved_files;
2174 struct CXUnsavedFile *unsaved_files;
2175 unsigned options;
2176 int result;
2177};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002178
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002179static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002180 ReparseTranslationUnitInfo *RTUI =
2181 static_cast<ReparseTranslationUnitInfo*>(UserData);
2182 CXTranslationUnit TU = RTUI->TU;
2183 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2184 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2185 unsigned options = RTUI->options;
2186 (void) options;
2187 RTUI->result = 1;
2188
Douglas Gregorabc563f2010-07-19 21:46:24 +00002189 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002190 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002191
2192 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2193 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002194
2195 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2196 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2197 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2198 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002199 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002200 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2201 Buffer));
2202 }
2203
Douglas Gregor593b0c12010-09-23 18:47:53 +00002204 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2205 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002206}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002207
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002208int clang_reparseTranslationUnit(CXTranslationUnit TU,
2209 unsigned num_unsaved_files,
2210 struct CXUnsavedFile *unsaved_files,
2211 unsigned options) {
2212 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2213 options, 0 };
2214 llvm::CrashRecoveryContext CRC;
2215
2216 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002217 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002218 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2219 return 1;
2220 }
2221
2222 return RTUI.result;
2223}
2224
Douglas Gregordf95a132010-08-09 20:45:32 +00002225
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002226CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002227 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002228 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002229
Steve Naroff77accc12009-09-03 18:19:54 +00002230 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002231 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002232}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002233
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002234CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002235 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002236 return Result;
2237}
2238
Ted Kremenekfb480492010-01-13 21:46:36 +00002239} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002240
Ted Kremenekfb480492010-01-13 21:46:36 +00002241//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002242// CXSourceLocation and CXSourceRange Operations.
2243//===----------------------------------------------------------------------===//
2244
Douglas Gregorb9790342010-01-22 21:44:22 +00002245extern "C" {
2246CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002247 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002248 return Result;
2249}
2250
2251unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002252 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2253 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2254 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002255}
2256
2257CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2258 CXFile file,
2259 unsigned line,
2260 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002261 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002262 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002263
Douglas Gregorb9790342010-01-22 21:44:22 +00002264 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2265 SourceLocation SLoc
2266 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002267 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002268 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002269
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002270 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002271}
2272
Douglas Gregor5352ac02010-01-28 00:27:43 +00002273CXSourceRange clang_getNullRange() {
2274 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2275 return Result;
2276}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002277
Douglas Gregor5352ac02010-01-28 00:27:43 +00002278CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2279 if (begin.ptr_data[0] != end.ptr_data[0] ||
2280 begin.ptr_data[1] != end.ptr_data[1])
2281 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002282
2283 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002284 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002285 return Result;
2286}
2287
Douglas Gregor46766dc2010-01-26 19:19:08 +00002288void clang_getInstantiationLocation(CXSourceLocation location,
2289 CXFile *file,
2290 unsigned *line,
2291 unsigned *column,
2292 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002293 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2294
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002295 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002296 if (file)
2297 *file = 0;
2298 if (line)
2299 *line = 0;
2300 if (column)
2301 *column = 0;
2302 if (offset)
2303 *offset = 0;
2304 return;
2305 }
2306
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002307 const SourceManager &SM =
2308 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002309 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002310
2311 if (file)
2312 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2313 if (line)
2314 *line = SM.getInstantiationLineNumber(InstLoc);
2315 if (column)
2316 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002317 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002318 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002319}
2320
Douglas Gregor1db19de2010-01-19 21:36:55 +00002321CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002322 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002323 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002324 return Result;
2325}
2326
2327CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002328 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002329 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002330 return Result;
2331}
2332
Douglas Gregorb9790342010-01-22 21:44:22 +00002333} // end: extern "C"
2334
Douglas Gregor1db19de2010-01-19 21:36:55 +00002335//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002336// CXFile Operations.
2337//===----------------------------------------------------------------------===//
2338
2339extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002340CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002341 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002342 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002343
Steve Naroff88145032009-10-27 14:35:18 +00002344 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002345 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002346}
2347
2348time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002349 if (!SFile)
2350 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002351
Steve Naroff88145032009-10-27 14:35:18 +00002352 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2353 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002354}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002355
Douglas Gregorb9790342010-01-22 21:44:22 +00002356CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2357 if (!tu)
2358 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002359
Douglas Gregorb9790342010-01-22 21:44:22 +00002360 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002361
Douglas Gregorb9790342010-01-22 21:44:22 +00002362 FileManager &FMgr = CXXUnit->getFileManager();
2363 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2364 return const_cast<FileEntry *>(File);
2365}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002366
Ted Kremenekfb480492010-01-13 21:46:36 +00002367} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002368
Ted Kremenekfb480492010-01-13 21:46:36 +00002369//===----------------------------------------------------------------------===//
2370// CXCursor Operations.
2371//===----------------------------------------------------------------------===//
2372
Ted Kremenekfb480492010-01-13 21:46:36 +00002373static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002374 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2375 return getDeclFromExpr(CE->getSubExpr());
2376
Ted Kremenekfb480492010-01-13 21:46:36 +00002377 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2378 return RefExpr->getDecl();
2379 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2380 return ME->getMemberDecl();
2381 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2382 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002383 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2384 return PRE->getProperty();
2385
Ted Kremenekfb480492010-01-13 21:46:36 +00002386 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2387 return getDeclFromExpr(CE->getCallee());
Ted Kremenekfb480492010-01-13 21:46:36 +00002388 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2389 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002390
Douglas Gregordb1314e2010-10-01 21:11:22 +00002391 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2392 return PE->getProtocol();
2393
Ted Kremenekfb480492010-01-13 21:46:36 +00002394 return 0;
2395}
2396
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002397static SourceLocation getLocationFromExpr(Expr *E) {
2398 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2399 return /*FIXME:*/Msg->getLeftLoc();
2400 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2401 return DRE->getLocation();
2402 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2403 return Member->getMemberLoc();
2404 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2405 return Ivar->getLocation();
2406 return E->getLocStart();
2407}
2408
Ted Kremenekfb480492010-01-13 21:46:36 +00002409extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002410
2411unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002412 CXCursorVisitor visitor,
2413 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002414 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002415
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002416 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2417 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002418 return CursorVis.VisitChildren(parent);
2419}
2420
Douglas Gregor78205d42010-01-20 21:45:58 +00002421static CXString getDeclSpelling(Decl *D) {
2422 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2423 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002424 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002425
Douglas Gregor78205d42010-01-20 21:45:58 +00002426 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002427 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002428
Douglas Gregor78205d42010-01-20 21:45:58 +00002429 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2430 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2431 // and returns different names. NamedDecl returns the class name and
2432 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002433 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002434
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002435 if (isa<UsingDirectiveDecl>(D))
2436 return createCXString("");
2437
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002438 llvm::SmallString<1024> S;
2439 llvm::raw_svector_ostream os(S);
2440 ND->printName(os);
2441
2442 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002443}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002444
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002445CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002446 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002447 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002448
Steve Narofff334b4e2009-09-02 18:26:48 +00002449 if (clang_isReference(C.kind)) {
2450 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002451 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002452 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002453 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002454 }
2455 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002456 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002457 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002458 }
2459 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002460 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002461 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002462 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002463 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002464 case CXCursor_CXXBaseSpecifier: {
2465 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2466 return createCXString(B->getType().getAsString());
2467 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002468 case CXCursor_TypeRef: {
2469 TypeDecl *Type = getCursorTypeRef(C).first;
2470 assert(Type && "Missing type decl");
2471
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002472 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2473 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002474 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002475 case CXCursor_TemplateRef: {
2476 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002477 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002478
2479 return createCXString(Template->getNameAsString());
2480 }
Douglas Gregor69319002010-08-31 23:48:11 +00002481
2482 case CXCursor_NamespaceRef: {
2483 NamedDecl *NS = getCursorNamespaceRef(C).first;
2484 assert(NS && "Missing namespace decl");
2485
2486 return createCXString(NS->getNameAsString());
2487 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002488
Douglas Gregora67e03f2010-09-09 21:42:20 +00002489 case CXCursor_MemberRef: {
2490 FieldDecl *Field = getCursorMemberRef(C).first;
2491 assert(Field && "Missing member decl");
2492
2493 return createCXString(Field->getNameAsString());
2494 }
2495
Douglas Gregor36897b02010-09-10 00:22:18 +00002496 case CXCursor_LabelRef: {
2497 LabelStmt *Label = getCursorLabelRef(C).first;
2498 assert(Label && "Missing label");
2499
2500 return createCXString(Label->getID()->getName());
2501 }
2502
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002503 case CXCursor_OverloadedDeclRef: {
2504 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2505 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2506 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2507 return createCXString(ND->getNameAsString());
2508 return createCXString("");
2509 }
2510 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2511 return createCXString(E->getName().getAsString());
2512 OverloadedTemplateStorage *Ovl
2513 = Storage.get<OverloadedTemplateStorage*>();
2514 if (Ovl->size() == 0)
2515 return createCXString("");
2516 return createCXString((*Ovl->begin())->getNameAsString());
2517 }
2518
Daniel Dunbaracca7252009-11-30 20:42:49 +00002519 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002520 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002521 }
2522 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002523
2524 if (clang_isExpression(C.kind)) {
2525 Decl *D = getDeclFromExpr(getCursorExpr(C));
2526 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002527 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002528 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002529 }
2530
Douglas Gregor36897b02010-09-10 00:22:18 +00002531 if (clang_isStatement(C.kind)) {
2532 Stmt *S = getCursorStmt(C);
2533 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2534 return createCXString(Label->getID()->getName());
2535
2536 return createCXString("");
2537 }
2538
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002539 if (C.kind == CXCursor_MacroInstantiation)
2540 return createCXString(getCursorMacroInstantiation(C)->getName()
2541 ->getNameStart());
2542
Douglas Gregor572feb22010-03-18 18:04:21 +00002543 if (C.kind == CXCursor_MacroDefinition)
2544 return createCXString(getCursorMacroDefinition(C)->getName()
2545 ->getNameStart());
2546
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002547 if (clang_isDeclaration(C.kind))
2548 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002549
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002550 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002551}
2552
Douglas Gregor358559d2010-10-02 22:49:11 +00002553CXString clang_getCursorDisplayName(CXCursor C) {
2554 if (!clang_isDeclaration(C.kind))
2555 return clang_getCursorSpelling(C);
2556
2557 Decl *D = getCursorDecl(C);
2558 if (!D)
2559 return createCXString("");
2560
2561 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2562 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2563 D = FunTmpl->getTemplatedDecl();
2564
2565 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2566 llvm::SmallString<64> Str;
2567 llvm::raw_svector_ostream OS(Str);
2568 OS << Function->getNameAsString();
2569 if (Function->getPrimaryTemplate())
2570 OS << "<>";
2571 OS << "(";
2572 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2573 if (I)
2574 OS << ", ";
2575 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2576 }
2577
2578 if (Function->isVariadic()) {
2579 if (Function->getNumParams())
2580 OS << ", ";
2581 OS << "...";
2582 }
2583 OS << ")";
2584 return createCXString(OS.str());
2585 }
2586
2587 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2588 llvm::SmallString<64> Str;
2589 llvm::raw_svector_ostream OS(Str);
2590 OS << ClassTemplate->getNameAsString();
2591 OS << "<";
2592 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2593 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2594 if (I)
2595 OS << ", ";
2596
2597 NamedDecl *Param = Params->getParam(I);
2598 if (Param->getIdentifier()) {
2599 OS << Param->getIdentifier()->getName();
2600 continue;
2601 }
2602
2603 // There is no parameter name, which makes this tricky. Try to come up
2604 // with something useful that isn't too long.
2605 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2606 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2607 else if (NonTypeTemplateParmDecl *NTTP
2608 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2609 OS << NTTP->getType().getAsString(Policy);
2610 else
2611 OS << "template<...> class";
2612 }
2613
2614 OS << ">";
2615 return createCXString(OS.str());
2616 }
2617
2618 if (ClassTemplateSpecializationDecl *ClassSpec
2619 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2620 // If the type was explicitly written, use that.
2621 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2622 return createCXString(TSInfo->getType().getAsString(Policy));
2623
2624 llvm::SmallString<64> Str;
2625 llvm::raw_svector_ostream OS(Str);
2626 OS << ClassSpec->getNameAsString();
2627 OS << TemplateSpecializationType::PrintTemplateArgumentList(
2628 ClassSpec->getTemplateArgs().getFlatArgumentList(),
2629 ClassSpec->getTemplateArgs().flat_size(),
2630 Policy);
2631 return createCXString(OS.str());
2632 }
2633
2634 return clang_getCursorSpelling(C);
2635}
2636
Ted Kremeneke68fff62010-02-17 00:41:32 +00002637CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002638 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002639 case CXCursor_FunctionDecl:
2640 return createCXString("FunctionDecl");
2641 case CXCursor_TypedefDecl:
2642 return createCXString("TypedefDecl");
2643 case CXCursor_EnumDecl:
2644 return createCXString("EnumDecl");
2645 case CXCursor_EnumConstantDecl:
2646 return createCXString("EnumConstantDecl");
2647 case CXCursor_StructDecl:
2648 return createCXString("StructDecl");
2649 case CXCursor_UnionDecl:
2650 return createCXString("UnionDecl");
2651 case CXCursor_ClassDecl:
2652 return createCXString("ClassDecl");
2653 case CXCursor_FieldDecl:
2654 return createCXString("FieldDecl");
2655 case CXCursor_VarDecl:
2656 return createCXString("VarDecl");
2657 case CXCursor_ParmDecl:
2658 return createCXString("ParmDecl");
2659 case CXCursor_ObjCInterfaceDecl:
2660 return createCXString("ObjCInterfaceDecl");
2661 case CXCursor_ObjCCategoryDecl:
2662 return createCXString("ObjCCategoryDecl");
2663 case CXCursor_ObjCProtocolDecl:
2664 return createCXString("ObjCProtocolDecl");
2665 case CXCursor_ObjCPropertyDecl:
2666 return createCXString("ObjCPropertyDecl");
2667 case CXCursor_ObjCIvarDecl:
2668 return createCXString("ObjCIvarDecl");
2669 case CXCursor_ObjCInstanceMethodDecl:
2670 return createCXString("ObjCInstanceMethodDecl");
2671 case CXCursor_ObjCClassMethodDecl:
2672 return createCXString("ObjCClassMethodDecl");
2673 case CXCursor_ObjCImplementationDecl:
2674 return createCXString("ObjCImplementationDecl");
2675 case CXCursor_ObjCCategoryImplDecl:
2676 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002677 case CXCursor_CXXMethod:
2678 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002679 case CXCursor_UnexposedDecl:
2680 return createCXString("UnexposedDecl");
2681 case CXCursor_ObjCSuperClassRef:
2682 return createCXString("ObjCSuperClassRef");
2683 case CXCursor_ObjCProtocolRef:
2684 return createCXString("ObjCProtocolRef");
2685 case CXCursor_ObjCClassRef:
2686 return createCXString("ObjCClassRef");
2687 case CXCursor_TypeRef:
2688 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002689 case CXCursor_TemplateRef:
2690 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002691 case CXCursor_NamespaceRef:
2692 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002693 case CXCursor_MemberRef:
2694 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002695 case CXCursor_LabelRef:
2696 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002697 case CXCursor_OverloadedDeclRef:
2698 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002699 case CXCursor_UnexposedExpr:
2700 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002701 case CXCursor_BlockExpr:
2702 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002703 case CXCursor_DeclRefExpr:
2704 return createCXString("DeclRefExpr");
2705 case CXCursor_MemberRefExpr:
2706 return createCXString("MemberRefExpr");
2707 case CXCursor_CallExpr:
2708 return createCXString("CallExpr");
2709 case CXCursor_ObjCMessageExpr:
2710 return createCXString("ObjCMessageExpr");
2711 case CXCursor_UnexposedStmt:
2712 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002713 case CXCursor_LabelStmt:
2714 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002715 case CXCursor_InvalidFile:
2716 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002717 case CXCursor_InvalidCode:
2718 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002719 case CXCursor_NoDeclFound:
2720 return createCXString("NoDeclFound");
2721 case CXCursor_NotImplemented:
2722 return createCXString("NotImplemented");
2723 case CXCursor_TranslationUnit:
2724 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002725 case CXCursor_UnexposedAttr:
2726 return createCXString("UnexposedAttr");
2727 case CXCursor_IBActionAttr:
2728 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002729 case CXCursor_IBOutletAttr:
2730 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002731 case CXCursor_IBOutletCollectionAttr:
2732 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002733 case CXCursor_PreprocessingDirective:
2734 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002735 case CXCursor_MacroDefinition:
2736 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002737 case CXCursor_MacroInstantiation:
2738 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002739 case CXCursor_Namespace:
2740 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002741 case CXCursor_LinkageSpec:
2742 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002743 case CXCursor_CXXBaseSpecifier:
2744 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002745 case CXCursor_Constructor:
2746 return createCXString("CXXConstructor");
2747 case CXCursor_Destructor:
2748 return createCXString("CXXDestructor");
2749 case CXCursor_ConversionFunction:
2750 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002751 case CXCursor_TemplateTypeParameter:
2752 return createCXString("TemplateTypeParameter");
2753 case CXCursor_NonTypeTemplateParameter:
2754 return createCXString("NonTypeTemplateParameter");
2755 case CXCursor_TemplateTemplateParameter:
2756 return createCXString("TemplateTemplateParameter");
2757 case CXCursor_FunctionTemplate:
2758 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002759 case CXCursor_ClassTemplate:
2760 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002761 case CXCursor_ClassTemplatePartialSpecialization:
2762 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002763 case CXCursor_NamespaceAlias:
2764 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002765 case CXCursor_UsingDirective:
2766 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002767 case CXCursor_UsingDeclaration:
2768 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002769 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002770
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002771 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002772 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002773}
Steve Naroff89922f82009-08-31 00:59:03 +00002774
Ted Kremeneke68fff62010-02-17 00:41:32 +00002775enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2776 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002777 CXClientData client_data) {
2778 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2779 *BestCursor = cursor;
2780 return CXChildVisit_Recurse;
2781}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002782
Douglas Gregorb9790342010-01-22 21:44:22 +00002783CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2784 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002785 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002786
Douglas Gregorb9790342010-01-22 21:44:22 +00002787 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002788 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2789
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002790 // Translate the given source location to make it point at the beginning of
2791 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002792 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002793
2794 // Guard against an invalid SourceLocation, or we may assert in one
2795 // of the following calls.
2796 if (SLoc.isInvalid())
2797 return clang_getNullCursor();
2798
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002799 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2800 CXXUnit->getASTContext().getLangOptions());
2801
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002802 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2803 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002804 // FIXME: Would be great to have a "hint" cursor, then walk from that
2805 // hint cursor upward until we find a cursor whose source range encloses
2806 // the region of interest, rather than starting from the translation unit.
2807 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002808 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002809 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002810 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002811 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002812 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002813}
2814
Ted Kremenek73885552009-11-17 19:28:59 +00002815CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002816 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002817}
2818
2819unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002820 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002821}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002822
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002823unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002824 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2825}
2826
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002827unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002828 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2829}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002830
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002831unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002832 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2833}
2834
Douglas Gregor97b98722010-01-19 23:20:36 +00002835unsigned clang_isExpression(enum CXCursorKind K) {
2836 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2837}
2838
2839unsigned clang_isStatement(enum CXCursorKind K) {
2840 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2841}
2842
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002843unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2844 return K == CXCursor_TranslationUnit;
2845}
2846
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002847unsigned clang_isPreprocessing(enum CXCursorKind K) {
2848 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2849}
2850
Ted Kremenekad6eff62010-03-08 21:17:29 +00002851unsigned clang_isUnexposed(enum CXCursorKind K) {
2852 switch (K) {
2853 case CXCursor_UnexposedDecl:
2854 case CXCursor_UnexposedExpr:
2855 case CXCursor_UnexposedStmt:
2856 case CXCursor_UnexposedAttr:
2857 return true;
2858 default:
2859 return false;
2860 }
2861}
2862
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002863CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002864 return C.kind;
2865}
2866
Douglas Gregor98258af2010-01-18 22:46:11 +00002867CXSourceLocation clang_getCursorLocation(CXCursor C) {
2868 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002869 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002870 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002871 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2872 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002873 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002874 }
2875
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002876 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002877 std::pair<ObjCProtocolDecl *, SourceLocation> P
2878 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002879 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002880 }
2881
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002882 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002883 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2884 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002885 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002886 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002887
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002888 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002889 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002890 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002891 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002892
2893 case CXCursor_TemplateRef: {
2894 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2895 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2896 }
2897
Douglas Gregor69319002010-08-31 23:48:11 +00002898 case CXCursor_NamespaceRef: {
2899 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2900 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2901 }
2902
Douglas Gregora67e03f2010-09-09 21:42:20 +00002903 case CXCursor_MemberRef: {
2904 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
2905 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2906 }
2907
Ted Kremenek3064ef92010-08-27 21:34:58 +00002908 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00002909 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
2910 if (!BaseSpec)
2911 return clang_getNullLocation();
2912
2913 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
2914 return cxloc::translateSourceLocation(getCursorContext(C),
2915 TSInfo->getTypeLoc().getBeginLoc());
2916
2917 return cxloc::translateSourceLocation(getCursorContext(C),
2918 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00002919 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002920
Douglas Gregor36897b02010-09-10 00:22:18 +00002921 case CXCursor_LabelRef: {
2922 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
2923 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
2924 }
2925
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002926 case CXCursor_OverloadedDeclRef:
2927 return cxloc::translateSourceLocation(getCursorContext(C),
2928 getCursorOverloadedDeclRef(C).second);
2929
Douglas Gregorf46034a2010-01-18 23:41:10 +00002930 default:
2931 // FIXME: Need a way to enumerate all non-reference cases.
2932 llvm_unreachable("Missed a reference kind");
2933 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002934 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002935
2936 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002937 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002938 getLocationFromExpr(getCursorExpr(C)));
2939
Douglas Gregor36897b02010-09-10 00:22:18 +00002940 if (clang_isStatement(C.kind))
2941 return cxloc::translateSourceLocation(getCursorContext(C),
2942 getCursorStmt(C)->getLocStart());
2943
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002944 if (C.kind == CXCursor_PreprocessingDirective) {
2945 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2946 return cxloc::translateSourceLocation(getCursorContext(C), L);
2947 }
Douglas Gregor48072312010-03-18 15:23:44 +00002948
2949 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002950 SourceLocation L
2951 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002952 return cxloc::translateSourceLocation(getCursorContext(C), L);
2953 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002954
2955 if (C.kind == CXCursor_MacroDefinition) {
2956 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2957 return cxloc::translateSourceLocation(getCursorContext(C), L);
2958 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002959
Ted Kremenek9a700d22010-05-12 06:16:13 +00002960 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002961 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002962
Douglas Gregorf46034a2010-01-18 23:41:10 +00002963 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002964 SourceLocation Loc = D->getLocation();
2965 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2966 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002967 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002968}
Douglas Gregora7bde202010-01-19 00:34:46 +00002969
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002970} // end extern "C"
2971
2972static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002973 if (clang_isReference(C.kind)) {
2974 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002975 case CXCursor_ObjCSuperClassRef:
2976 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002977
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002978 case CXCursor_ObjCProtocolRef:
2979 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002980
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002981 case CXCursor_ObjCClassRef:
2982 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002983
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002984 case CXCursor_TypeRef:
2985 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002986
2987 case CXCursor_TemplateRef:
2988 return getCursorTemplateRef(C).second;
2989
Douglas Gregor69319002010-08-31 23:48:11 +00002990 case CXCursor_NamespaceRef:
2991 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00002992
2993 case CXCursor_MemberRef:
2994 return getCursorMemberRef(C).second;
2995
Ted Kremenek3064ef92010-08-27 21:34:58 +00002996 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00002997 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002998
Douglas Gregor36897b02010-09-10 00:22:18 +00002999 case CXCursor_LabelRef:
3000 return getCursorLabelRef(C).second;
3001
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003002 case CXCursor_OverloadedDeclRef:
3003 return getCursorOverloadedDeclRef(C).second;
3004
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003005 default:
3006 // FIXME: Need a way to enumerate all non-reference cases.
3007 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003008 }
3009 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003010
3011 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003012 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003013
3014 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003015 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003016
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003017 if (C.kind == CXCursor_PreprocessingDirective)
3018 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003019
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003020 if (C.kind == CXCursor_MacroInstantiation)
3021 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003022
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003023 if (C.kind == CXCursor_MacroDefinition)
3024 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003025
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003026 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
3027 return getCursorDecl(C)->getSourceRange();
3028
3029 return SourceRange();
3030}
3031
3032extern "C" {
3033
3034CXSourceRange clang_getCursorExtent(CXCursor C) {
3035 SourceRange R = getRawCursorExtent(C);
3036 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003037 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003038
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003039 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003040}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003041
3042CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003043 if (clang_isInvalid(C.kind))
3044 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003045
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003046 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003047 if (clang_isDeclaration(C.kind)) {
3048 Decl *D = getCursorDecl(C);
3049 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3050 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3051 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3052 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3053 if (ObjCForwardProtocolDecl *Protocols
3054 = dyn_cast<ObjCForwardProtocolDecl>(D))
3055 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3056
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003057 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003058 }
3059
Douglas Gregor97b98722010-01-19 23:20:36 +00003060 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003061 Expr *E = getCursorExpr(C);
3062 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003063 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003064 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003065
3066 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3067 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3068
Douglas Gregor97b98722010-01-19 23:20:36 +00003069 return clang_getNullCursor();
3070 }
3071
Douglas Gregor36897b02010-09-10 00:22:18 +00003072 if (clang_isStatement(C.kind)) {
3073 Stmt *S = getCursorStmt(C);
3074 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3075 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3076 getCursorASTUnit(C));
3077
3078 return clang_getNullCursor();
3079 }
3080
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003081 if (C.kind == CXCursor_MacroInstantiation) {
3082 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3083 return MakeMacroDefinitionCursor(Def, CXXUnit);
3084 }
3085
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003086 if (!clang_isReference(C.kind))
3087 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003088
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003089 switch (C.kind) {
3090 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003091 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003092
3093 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003094 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003095
3096 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003097 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003098
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003099 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003100 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003101
3102 case CXCursor_TemplateRef:
3103 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3104
Douglas Gregor69319002010-08-31 23:48:11 +00003105 case CXCursor_NamespaceRef:
3106 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3107
Douglas Gregora67e03f2010-09-09 21:42:20 +00003108 case CXCursor_MemberRef:
3109 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3110
Ted Kremenek3064ef92010-08-27 21:34:58 +00003111 case CXCursor_CXXBaseSpecifier: {
3112 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3113 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3114 CXXUnit));
3115 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003116
Douglas Gregor36897b02010-09-10 00:22:18 +00003117 case CXCursor_LabelRef:
3118 // FIXME: We end up faking the "parent" declaration here because we
3119 // don't want to make CXCursor larger.
3120 return MakeCXCursor(getCursorLabelRef(C).first,
3121 CXXUnit->getASTContext().getTranslationUnitDecl(),
3122 CXXUnit);
3123
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003124 case CXCursor_OverloadedDeclRef:
3125 return C;
3126
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003127 default:
3128 // We would prefer to enumerate all non-reference cursor kinds here.
3129 llvm_unreachable("Unhandled reference cursor kind");
3130 break;
3131 }
3132 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003133
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003134 return clang_getNullCursor();
3135}
3136
Douglas Gregorb6998662010-01-19 19:34:47 +00003137CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003138 if (clang_isInvalid(C.kind))
3139 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003140
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003141 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003142
Douglas Gregorb6998662010-01-19 19:34:47 +00003143 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003144 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003145 C = clang_getCursorReferenced(C);
3146 WasReference = true;
3147 }
3148
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003149 if (C.kind == CXCursor_MacroInstantiation)
3150 return clang_getCursorReferenced(C);
3151
Douglas Gregorb6998662010-01-19 19:34:47 +00003152 if (!clang_isDeclaration(C.kind))
3153 return clang_getNullCursor();
3154
3155 Decl *D = getCursorDecl(C);
3156 if (!D)
3157 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003158
Douglas Gregorb6998662010-01-19 19:34:47 +00003159 switch (D->getKind()) {
3160 // Declaration kinds that don't really separate the notions of
3161 // declaration and definition.
3162 case Decl::Namespace:
3163 case Decl::Typedef:
3164 case Decl::TemplateTypeParm:
3165 case Decl::EnumConstant:
3166 case Decl::Field:
3167 case Decl::ObjCIvar:
3168 case Decl::ObjCAtDefsField:
3169 case Decl::ImplicitParam:
3170 case Decl::ParmVar:
3171 case Decl::NonTypeTemplateParm:
3172 case Decl::TemplateTemplateParm:
3173 case Decl::ObjCCategoryImpl:
3174 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003175 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003176 case Decl::LinkageSpec:
3177 case Decl::ObjCPropertyImpl:
3178 case Decl::FileScopeAsm:
3179 case Decl::StaticAssert:
3180 case Decl::Block:
3181 return C;
3182
3183 // Declaration kinds that don't make any sense here, but are
3184 // nonetheless harmless.
3185 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003186 break;
3187
3188 // Declaration kinds for which the definition is not resolvable.
3189 case Decl::UnresolvedUsingTypename:
3190 case Decl::UnresolvedUsingValue:
3191 break;
3192
3193 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003194 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3195 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003196
3197 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003198 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003199
3200 case Decl::Enum:
3201 case Decl::Record:
3202 case Decl::CXXRecord:
3203 case Decl::ClassTemplateSpecialization:
3204 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003205 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003206 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003207 return clang_getNullCursor();
3208
3209 case Decl::Function:
3210 case Decl::CXXMethod:
3211 case Decl::CXXConstructor:
3212 case Decl::CXXDestructor:
3213 case Decl::CXXConversion: {
3214 const FunctionDecl *Def = 0;
3215 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003216 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003217 return clang_getNullCursor();
3218 }
3219
3220 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003221 // Ask the variable if it has a definition.
3222 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3223 return MakeCXCursor(Def, CXXUnit);
3224 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003225 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003226
Douglas Gregorb6998662010-01-19 19:34:47 +00003227 case Decl::FunctionTemplate: {
3228 const FunctionDecl *Def = 0;
3229 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003230 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003231 return clang_getNullCursor();
3232 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003233
Douglas Gregorb6998662010-01-19 19:34:47 +00003234 case Decl::ClassTemplate: {
3235 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003236 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003237 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003238 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003239 return clang_getNullCursor();
3240 }
3241
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003242 case Decl::Using:
3243 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3244 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003245
3246 case Decl::UsingShadow:
3247 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003248 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003249 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003250
3251 case Decl::ObjCMethod: {
3252 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3253 if (Method->isThisDeclarationADefinition())
3254 return C;
3255
3256 // Dig out the method definition in the associated
3257 // @implementation, if we have it.
3258 // FIXME: The ASTs should make finding the definition easier.
3259 if (ObjCInterfaceDecl *Class
3260 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3261 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3262 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3263 Method->isInstanceMethod()))
3264 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003265 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003266
3267 return clang_getNullCursor();
3268 }
3269
3270 case Decl::ObjCCategory:
3271 if (ObjCCategoryImplDecl *Impl
3272 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003273 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003274 return clang_getNullCursor();
3275
3276 case Decl::ObjCProtocol:
3277 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3278 return C;
3279 return clang_getNullCursor();
3280
3281 case Decl::ObjCInterface:
3282 // There are two notions of a "definition" for an Objective-C
3283 // class: the interface and its implementation. When we resolved a
3284 // reference to an Objective-C class, produce the @interface as
3285 // the definition; when we were provided with the interface,
3286 // produce the @implementation as the definition.
3287 if (WasReference) {
3288 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3289 return C;
3290 } else if (ObjCImplementationDecl *Impl
3291 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003292 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003293 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003294
Douglas Gregorb6998662010-01-19 19:34:47 +00003295 case Decl::ObjCProperty:
3296 // FIXME: We don't really know where to find the
3297 // ObjCPropertyImplDecls that implement this property.
3298 return clang_getNullCursor();
3299
3300 case Decl::ObjCCompatibleAlias:
3301 if (ObjCInterfaceDecl *Class
3302 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3303 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003304 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003305
Douglas Gregorb6998662010-01-19 19:34:47 +00003306 return clang_getNullCursor();
3307
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003308 case Decl::ObjCForwardProtocol:
3309 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3310 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003311
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003312 case Decl::ObjCClass:
3313 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3314 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003315
3316 case Decl::Friend:
3317 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003318 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003319 return clang_getNullCursor();
3320
3321 case Decl::FriendTemplate:
3322 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003323 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003324 return clang_getNullCursor();
3325 }
3326
3327 return clang_getNullCursor();
3328}
3329
3330unsigned clang_isCursorDefinition(CXCursor C) {
3331 if (!clang_isDeclaration(C.kind))
3332 return 0;
3333
3334 return clang_getCursorDefinition(C) == C;
3335}
3336
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003337unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003338 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003339 return 0;
3340
3341 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3342 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3343 return E->getNumDecls();
3344
3345 if (OverloadedTemplateStorage *S
3346 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3347 return S->size();
3348
3349 Decl *D = Storage.get<Decl*>();
3350 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3351 return Using->getNumShadowDecls();
3352 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3353 return Classes->size();
3354 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3355 return Protocols->protocol_size();
3356
3357 return 0;
3358}
3359
3360CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003361 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003362 return clang_getNullCursor();
3363
3364 if (index >= clang_getNumOverloadedDecls(cursor))
3365 return clang_getNullCursor();
3366
3367 ASTUnit *Unit = getCursorASTUnit(cursor);
3368 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3369 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3370 return MakeCXCursor(E->decls_begin()[index], Unit);
3371
3372 if (OverloadedTemplateStorage *S
3373 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3374 return MakeCXCursor(S->begin()[index], Unit);
3375
3376 Decl *D = Storage.get<Decl*>();
3377 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3378 // FIXME: This is, unfortunately, linear time.
3379 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3380 std::advance(Pos, index);
3381 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3382 }
3383
3384 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3385 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3386
3387 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3388 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3389
3390 return clang_getNullCursor();
3391}
3392
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003393void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003394 const char **startBuf,
3395 const char **endBuf,
3396 unsigned *startLine,
3397 unsigned *startColumn,
3398 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003399 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003400 assert(getCursorDecl(C) && "CXCursor has null decl");
3401 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003402 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3403 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003404
Steve Naroff4ade6d62009-09-23 17:52:52 +00003405 SourceManager &SM = FD->getASTContext().getSourceManager();
3406 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3407 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3408 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3409 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3410 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3411 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3412}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003413
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003414void clang_enableStackTraces(void) {
3415 llvm::sys::PrintStackTraceOnErrorSignal();
3416}
3417
Ted Kremenekfb480492010-01-13 21:46:36 +00003418} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003419
Ted Kremenekfb480492010-01-13 21:46:36 +00003420//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003421// Token-based Operations.
3422//===----------------------------------------------------------------------===//
3423
3424/* CXToken layout:
3425 * int_data[0]: a CXTokenKind
3426 * int_data[1]: starting token location
3427 * int_data[2]: token length
3428 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003429 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003430 * otherwise unused.
3431 */
3432extern "C" {
3433
3434CXTokenKind clang_getTokenKind(CXToken CXTok) {
3435 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3436}
3437
3438CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3439 switch (clang_getTokenKind(CXTok)) {
3440 case CXToken_Identifier:
3441 case CXToken_Keyword:
3442 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003443 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3444 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003445
3446 case CXToken_Literal: {
3447 // We have stashed the starting pointer in the ptr_data field. Use it.
3448 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003449 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003450 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003451
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003452 case CXToken_Punctuation:
3453 case CXToken_Comment:
3454 break;
3455 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003456
3457 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003458 // deconstructing the source location.
3459 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3460 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003461 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003462
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003463 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3464 std::pair<FileID, unsigned> LocInfo
3465 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003466 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003467 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003468 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3469 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003470 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003471
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003472 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003473}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003474
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003475CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3476 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3477 if (!CXXUnit)
3478 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003479
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003480 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3481 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3482}
3483
3484CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3485 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003486 if (!CXXUnit)
3487 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003488
3489 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003490 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3491}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003492
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003493void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3494 CXToken **Tokens, unsigned *NumTokens) {
3495 if (Tokens)
3496 *Tokens = 0;
3497 if (NumTokens)
3498 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003499
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003500 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3501 if (!CXXUnit || !Tokens || !NumTokens)
3502 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003503
Douglas Gregorbdf60622010-03-05 21:16:25 +00003504 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3505
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003506 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003507 if (R.isInvalid())
3508 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003509
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003510 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3511 std::pair<FileID, unsigned> BeginLocInfo
3512 = SourceMgr.getDecomposedLoc(R.getBegin());
3513 std::pair<FileID, unsigned> EndLocInfo
3514 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003515
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003516 // Cannot tokenize across files.
3517 if (BeginLocInfo.first != EndLocInfo.first)
3518 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003519
3520 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003521 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003522 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003523 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003524 if (Invalid)
3525 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003526
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003527 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3528 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003529 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003530 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003531
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003532 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003533 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003534 llvm::SmallVector<CXToken, 32> CXTokens;
3535 Token Tok;
3536 do {
3537 // Lex the next token
3538 Lex.LexFromRawLexer(Tok);
3539 if (Tok.is(tok::eof))
3540 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003541
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003542 // Initialize the CXToken.
3543 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003544
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003545 // - Common fields
3546 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3547 CXTok.int_data[2] = Tok.getLength();
3548 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003549
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003550 // - Kind-specific fields
3551 if (Tok.isLiteral()) {
3552 CXTok.int_data[0] = CXToken_Literal;
3553 CXTok.ptr_data = (void *)Tok.getLiteralData();
3554 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003555 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003556 std::pair<FileID, unsigned> LocInfo
3557 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003558 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003559 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003560 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3561 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003562 return;
3563
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003564 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003565 IdentifierInfo *II
3566 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003567
3568 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3569 CXTok.int_data[0] = CXToken_Keyword;
3570 }
3571 else {
3572 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3573 CXToken_Identifier
3574 : CXToken_Keyword;
3575 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003576 CXTok.ptr_data = II;
3577 } else if (Tok.is(tok::comment)) {
3578 CXTok.int_data[0] = CXToken_Comment;
3579 CXTok.ptr_data = 0;
3580 } else {
3581 CXTok.int_data[0] = CXToken_Punctuation;
3582 CXTok.ptr_data = 0;
3583 }
3584 CXTokens.push_back(CXTok);
3585 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003586
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003587 if (CXTokens.empty())
3588 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003589
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003590 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3591 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3592 *NumTokens = CXTokens.size();
3593}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003594
Ted Kremenek6db61092010-05-05 00:55:15 +00003595void clang_disposeTokens(CXTranslationUnit TU,
3596 CXToken *Tokens, unsigned NumTokens) {
3597 free(Tokens);
3598}
3599
3600} // end: extern "C"
3601
3602//===----------------------------------------------------------------------===//
3603// Token annotation APIs.
3604//===----------------------------------------------------------------------===//
3605
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003606typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003607static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3608 CXCursor parent,
3609 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003610namespace {
3611class AnnotateTokensWorker {
3612 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003613 CXToken *Tokens;
3614 CXCursor *Cursors;
3615 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003616 unsigned TokIdx;
3617 CursorVisitor AnnotateVis;
3618 SourceManager &SrcMgr;
3619
3620 bool MoreTokens() const { return TokIdx < NumTokens; }
3621 unsigned NextToken() const { return TokIdx; }
3622 void AdvanceToken() { ++TokIdx; }
3623 SourceLocation GetTokenLoc(unsigned tokI) {
3624 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3625 }
3626
Ted Kremenek6db61092010-05-05 00:55:15 +00003627public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003628 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003629 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3630 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003631 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003632 NumTokens(numTokens), TokIdx(0),
3633 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3634 Decl::MaxPCHLevel, RegionOfInterest),
3635 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003636
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003637 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003638 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003639 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003640};
3641}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003642
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003643void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3644 // Walk the AST within the region of interest, annotating tokens
3645 // along the way.
3646 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003647
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003648 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3649 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3650 if (Pos != Annotated.end())
3651 Cursors[I] = Pos->second;
3652 }
3653
3654 // Finish up annotating any tokens left.
3655 if (!MoreTokens())
3656 return;
3657
3658 const CXCursor &C = clang_getNullCursor();
3659 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3660 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3661 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003662 }
3663}
3664
Ted Kremenek6db61092010-05-05 00:55:15 +00003665enum CXChildVisitResult
3666AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003667 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3668 // We can always annotate a preprocessing directive/macro instantiation.
3669 if (clang_isPreprocessing(cursor.kind)) {
3670 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003671 return CXChildVisit_Recurse;
3672 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003673
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003674 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003675
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003676 if (cursorRange.isInvalid())
3677 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003678
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003679 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3680
Ted Kremeneka333c662010-05-12 05:29:33 +00003681 // Adjust the annotated range based specific declarations.
3682 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3683 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003684 Decl *D = cxcursor::getCursorDecl(cursor);
3685 // Don't visit synthesized ObjC methods, since they have no syntatic
3686 // representation in the source.
3687 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3688 if (MD->isSynthesized())
3689 return CXChildVisit_Continue;
3690 }
3691 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003692 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3693 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003694 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003695 if (TLoc.isValid() &&
3696 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003697 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003698 }
3699 }
3700 }
3701
Ted Kremenek3f404602010-08-14 01:14:06 +00003702 // If the location of the cursor occurs within a macro instantiation, record
3703 // the spelling location of the cursor in our annotation map. We can then
3704 // paper over the token labelings during a post-processing step to try and
3705 // get cursor mappings for tokens that are the *arguments* of a macro
3706 // instantiation.
3707 if (L.isMacroID()) {
3708 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3709 // Only invalidate the old annotation if it isn't part of a preprocessing
3710 // directive. Here we assume that the default construction of CXCursor
3711 // results in CXCursor.kind being an initialized value (i.e., 0). If
3712 // this isn't the case, we can fix by doing lookup + insertion.
3713
3714 CXCursor &oldC = Annotated[rawEncoding];
3715 if (!clang_isPreprocessing(oldC.kind))
3716 oldC = cursor;
3717 }
3718
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003719 const enum CXCursorKind K = clang_getCursorKind(parent);
3720 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003721 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3722 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003723
3724 while (MoreTokens()) {
3725 const unsigned I = NextToken();
3726 SourceLocation TokLoc = GetTokenLoc(I);
3727 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3728 case RangeBefore:
3729 Cursors[I] = updateC;
3730 AdvanceToken();
3731 continue;
3732 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003733 case RangeOverlap:
3734 break;
3735 }
3736 break;
3737 }
3738
3739 // Visit children to get their cursor information.
3740 const unsigned BeforeChildren = NextToken();
3741 VisitChildren(cursor);
3742 const unsigned AfterChildren = NextToken();
3743
3744 // Adjust 'Last' to the last token within the extent of the cursor.
3745 while (MoreTokens()) {
3746 const unsigned I = NextToken();
3747 SourceLocation TokLoc = GetTokenLoc(I);
3748 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3749 case RangeBefore:
3750 assert(0 && "Infeasible");
3751 case RangeAfter:
3752 break;
3753 case RangeOverlap:
3754 Cursors[I] = updateC;
3755 AdvanceToken();
3756 continue;
3757 }
3758 break;
3759 }
3760 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003761
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003762 // Scan the tokens that are at the beginning of the cursor, but are not
3763 // capture by the child cursors.
3764
3765 // For AST elements within macros, rely on a post-annotate pass to
3766 // to correctly annotate the tokens with cursors. Otherwise we can
3767 // get confusing results of having tokens that map to cursors that really
3768 // are expanded by an instantiation.
3769 if (L.isMacroID())
3770 cursor = clang_getNullCursor();
3771
3772 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3773 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3774 break;
3775 Cursors[I] = cursor;
3776 }
3777 // Scan the tokens that are at the end of the cursor, but are not captured
3778 // but the child cursors.
3779 for (unsigned I = AfterChildren; I != Last; ++I)
3780 Cursors[I] = cursor;
3781
3782 TokIdx = Last;
3783 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003784}
3785
Ted Kremenek6db61092010-05-05 00:55:15 +00003786static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3787 CXCursor parent,
3788 CXClientData client_data) {
3789 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3790}
3791
3792extern "C" {
3793
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003794void clang_annotateTokens(CXTranslationUnit TU,
3795 CXToken *Tokens, unsigned NumTokens,
3796 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003797
3798 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003799 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003800
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003801 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003802 if (!CXXUnit) {
3803 // Any token we don't specifically annotate will have a NULL cursor.
3804 const CXCursor &C = clang_getNullCursor();
3805 for (unsigned I = 0; I != NumTokens; ++I)
3806 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003807 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003808 }
3809
Douglas Gregorbdf60622010-03-05 21:16:25 +00003810 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003811
Douglas Gregor0396f462010-03-19 05:22:59 +00003812 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003813 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003814 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3815 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003816 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3817 clang_getTokenLocation(TU,
3818 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003819
Douglas Gregor0396f462010-03-19 05:22:59 +00003820 // A mapping from the source locations found when re-lexing or traversing the
3821 // region of interest to the corresponding cursors.
3822 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003823
3824 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003825 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003826 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3827 std::pair<FileID, unsigned> BeginLocInfo
3828 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3829 std::pair<FileID, unsigned> EndLocInfo
3830 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003831
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003832 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003833 bool Invalid = false;
3834 if (BeginLocInfo.first == EndLocInfo.first &&
3835 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3836 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003837 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3838 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003839 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003840 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003841 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003842
3843 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003844 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003845 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003846 Token Tok;
3847 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003848
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003849 reprocess:
3850 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3851 // We have found a preprocessing directive. Gobble it up so that we
3852 // don't see it while preprocessing these tokens later, but keep track of
3853 // all of the token locations inside this preprocessing directive so that
3854 // we can annotate them appropriately.
3855 //
3856 // FIXME: Some simple tests here could identify macro definitions and
3857 // #undefs, to provide specific cursor kinds for those.
3858 std::vector<SourceLocation> Locations;
3859 do {
3860 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003861 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003862 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003863
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003864 using namespace cxcursor;
3865 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003866 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3867 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003868 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003869 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3870 Annotated[Locations[I].getRawEncoding()] = Cursor;
3871 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003872
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003873 if (Tok.isAtStartOfLine())
3874 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003875
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003876 continue;
3877 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003878
Douglas Gregor48072312010-03-18 15:23:44 +00003879 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003880 break;
3881 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003882 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003883
Douglas Gregor0396f462010-03-19 05:22:59 +00003884 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003885 // a specific cursor.
3886 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3887 CXXUnit, RegionOfInterest);
3888 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003889}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003890} // end: extern "C"
3891
3892//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003893// Operations for querying linkage of a cursor.
3894//===----------------------------------------------------------------------===//
3895
3896extern "C" {
3897CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003898 if (!clang_isDeclaration(cursor.kind))
3899 return CXLinkage_Invalid;
3900
Ted Kremenek16b42592010-03-03 06:36:57 +00003901 Decl *D = cxcursor::getCursorDecl(cursor);
3902 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3903 switch (ND->getLinkage()) {
3904 case NoLinkage: return CXLinkage_NoLinkage;
3905 case InternalLinkage: return CXLinkage_Internal;
3906 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3907 case ExternalLinkage: return CXLinkage_External;
3908 };
3909
3910 return CXLinkage_Invalid;
3911}
3912} // end: extern "C"
3913
3914//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003915// Operations for querying language of a cursor.
3916//===----------------------------------------------------------------------===//
3917
3918static CXLanguageKind getDeclLanguage(const Decl *D) {
3919 switch (D->getKind()) {
3920 default:
3921 break;
3922 case Decl::ImplicitParam:
3923 case Decl::ObjCAtDefsField:
3924 case Decl::ObjCCategory:
3925 case Decl::ObjCCategoryImpl:
3926 case Decl::ObjCClass:
3927 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003928 case Decl::ObjCForwardProtocol:
3929 case Decl::ObjCImplementation:
3930 case Decl::ObjCInterface:
3931 case Decl::ObjCIvar:
3932 case Decl::ObjCMethod:
3933 case Decl::ObjCProperty:
3934 case Decl::ObjCPropertyImpl:
3935 case Decl::ObjCProtocol:
3936 return CXLanguage_ObjC;
3937 case Decl::CXXConstructor:
3938 case Decl::CXXConversion:
3939 case Decl::CXXDestructor:
3940 case Decl::CXXMethod:
3941 case Decl::CXXRecord:
3942 case Decl::ClassTemplate:
3943 case Decl::ClassTemplatePartialSpecialization:
3944 case Decl::ClassTemplateSpecialization:
3945 case Decl::Friend:
3946 case Decl::FriendTemplate:
3947 case Decl::FunctionTemplate:
3948 case Decl::LinkageSpec:
3949 case Decl::Namespace:
3950 case Decl::NamespaceAlias:
3951 case Decl::NonTypeTemplateParm:
3952 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003953 case Decl::TemplateTemplateParm:
3954 case Decl::TemplateTypeParm:
3955 case Decl::UnresolvedUsingTypename:
3956 case Decl::UnresolvedUsingValue:
3957 case Decl::Using:
3958 case Decl::UsingDirective:
3959 case Decl::UsingShadow:
3960 return CXLanguage_CPlusPlus;
3961 }
3962
3963 return CXLanguage_C;
3964}
3965
3966extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003967
3968enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3969 if (clang_isDeclaration(cursor.kind))
3970 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3971 if (D->hasAttr<UnavailableAttr>() ||
3972 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3973 return CXAvailability_Available;
3974
3975 if (D->hasAttr<DeprecatedAttr>())
3976 return CXAvailability_Deprecated;
3977 }
3978
3979 return CXAvailability_Available;
3980}
3981
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003982CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3983 if (clang_isDeclaration(cursor.kind))
3984 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3985
3986 return CXLanguage_Invalid;
3987}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00003988
3989CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
3990 if (clang_isDeclaration(cursor.kind)) {
3991 if (Decl *D = getCursorDecl(cursor)) {
3992 DeclContext *DC = D->getDeclContext();
3993 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
3994 }
3995 }
3996
3997 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
3998 if (Decl *D = getCursorDecl(cursor))
3999 return MakeCXCursor(D, getCursorASTUnit(cursor));
4000 }
4001
4002 return clang_getNullCursor();
4003}
4004
4005CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4006 if (clang_isDeclaration(cursor.kind)) {
4007 if (Decl *D = getCursorDecl(cursor)) {
4008 DeclContext *DC = D->getLexicalDeclContext();
4009 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4010 }
4011 }
4012
4013 // FIXME: Note that we can't easily compute the lexical context of a
4014 // statement or expression, so we return nothing.
4015 return clang_getNullCursor();
4016}
4017
Douglas Gregor9f592342010-10-01 20:25:15 +00004018static void CollectOverriddenMethods(DeclContext *Ctx,
4019 ObjCMethodDecl *Method,
4020 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4021 if (!Ctx)
4022 return;
4023
4024 // If we have a class or category implementation, jump straight to the
4025 // interface.
4026 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4027 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4028
4029 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4030 if (!Container)
4031 return;
4032
4033 // Check whether we have a matching method at this level.
4034 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4035 Method->isInstanceMethod()))
4036 if (Method != Overridden) {
4037 // We found an override at this level; there is no need to look
4038 // into other protocols or categories.
4039 Methods.push_back(Overridden);
4040 return;
4041 }
4042
4043 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4044 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4045 PEnd = Protocol->protocol_end();
4046 P != PEnd; ++P)
4047 CollectOverriddenMethods(*P, Method, Methods);
4048 }
4049
4050 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4051 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4052 PEnd = Category->protocol_end();
4053 P != PEnd; ++P)
4054 CollectOverriddenMethods(*P, Method, Methods);
4055 }
4056
4057 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4058 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4059 PEnd = Interface->protocol_end();
4060 P != PEnd; ++P)
4061 CollectOverriddenMethods(*P, Method, Methods);
4062
4063 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4064 Category; Category = Category->getNextClassCategory())
4065 CollectOverriddenMethods(Category, Method, Methods);
4066
4067 // We only look into the superclass if we haven't found anything yet.
4068 if (Methods.empty())
4069 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4070 return CollectOverriddenMethods(Super, Method, Methods);
4071 }
4072}
4073
4074void clang_getOverriddenCursors(CXCursor cursor,
4075 CXCursor **overridden,
4076 unsigned *num_overridden) {
4077 if (overridden)
4078 *overridden = 0;
4079 if (num_overridden)
4080 *num_overridden = 0;
4081 if (!overridden || !num_overridden)
4082 return;
4083
4084 if (!clang_isDeclaration(cursor.kind))
4085 return;
4086
4087 Decl *D = getCursorDecl(cursor);
4088 if (!D)
4089 return;
4090
4091 // Handle C++ member functions.
4092 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4093 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4094 *num_overridden = CXXMethod->size_overridden_methods();
4095 if (!*num_overridden)
4096 return;
4097
4098 *overridden = new CXCursor [*num_overridden];
4099 unsigned I = 0;
4100 for (CXXMethodDecl::method_iterator
4101 M = CXXMethod->begin_overridden_methods(),
4102 MEnd = CXXMethod->end_overridden_methods();
4103 M != MEnd; (void)++M, ++I)
4104 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4105 return;
4106 }
4107
4108 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4109 if (!Method)
4110 return;
4111
4112 // Handle Objective-C methods.
4113 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4114 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4115
4116 if (Methods.empty())
4117 return;
4118
4119 *num_overridden = Methods.size();
4120 *overridden = new CXCursor [Methods.size()];
4121 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4122 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4123}
4124
4125void clang_disposeOverriddenCursors(CXCursor *overridden) {
4126 delete [] overridden;
4127}
4128
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004129} // end: extern "C"
4130
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004131
4132//===----------------------------------------------------------------------===//
4133// C++ AST instrospection.
4134//===----------------------------------------------------------------------===//
4135
4136extern "C" {
4137unsigned clang_CXXMethod_isStatic(CXCursor C) {
4138 if (!clang_isDeclaration(C.kind))
4139 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004140
4141 CXXMethodDecl *Method = 0;
4142 Decl *D = cxcursor::getCursorDecl(C);
4143 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4144 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4145 else
4146 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4147 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004148}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004149
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004150} // end: extern "C"
4151
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004152//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004153// Attribute introspection.
4154//===----------------------------------------------------------------------===//
4155
4156extern "C" {
4157CXType clang_getIBOutletCollectionType(CXCursor C) {
4158 if (C.kind != CXCursor_IBOutletCollectionAttr)
4159 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4160
4161 IBOutletCollectionAttr *A =
4162 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4163
4164 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4165}
4166} // end: extern "C"
4167
4168//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004169// CXString Operations.
4170//===----------------------------------------------------------------------===//
4171
4172extern "C" {
4173const char *clang_getCString(CXString string) {
4174 return string.Spelling;
4175}
4176
4177void clang_disposeString(CXString string) {
4178 if (string.MustFreeString && string.Spelling)
4179 free((void*)string.Spelling);
4180}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004181
Ted Kremenekfb480492010-01-13 21:46:36 +00004182} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004183
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004184namespace clang { namespace cxstring {
4185CXString createCXString(const char *String, bool DupString){
4186 CXString Str;
4187 if (DupString) {
4188 Str.Spelling = strdup(String);
4189 Str.MustFreeString = 1;
4190 } else {
4191 Str.Spelling = String;
4192 Str.MustFreeString = 0;
4193 }
4194 return Str;
4195}
4196
4197CXString createCXString(llvm::StringRef String, bool DupString) {
4198 CXString Result;
4199 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4200 char *Spelling = (char *)malloc(String.size() + 1);
4201 memmove(Spelling, String.data(), String.size());
4202 Spelling[String.size()] = 0;
4203 Result.Spelling = Spelling;
4204 Result.MustFreeString = 1;
4205 } else {
4206 Result.Spelling = String.data();
4207 Result.MustFreeString = 0;
4208 }
4209 return Result;
4210}
4211}}
4212
Ted Kremenek04bb7162010-01-22 22:44:15 +00004213//===----------------------------------------------------------------------===//
4214// Misc. utility functions.
4215//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004216
Ted Kremenek04bb7162010-01-22 22:44:15 +00004217extern "C" {
4218
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004219CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004220 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004221}
4222
4223} // end: extern "C"