blob: 3262016c2b1214a0a7b1350a46e361a1b70478c5 [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 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000558
559 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
560 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
561 return true;
562
563 continue;
564 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000565 }
566 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000567 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000568 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000569
Douglas Gregorb1373d02010-01-20 20:59:29 +0000570 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000571 return false;
572}
573
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000574bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000575 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
576 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000577
Ted Kremenek664cffd2010-07-22 11:30:19 +0000578 if (Stmt *Body = B->getBody())
579 return Visit(MakeCXCursor(Body, StmtParent, TU));
580
581 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000582}
583
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000585 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000586 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000587
Ted Kremenek23173d72010-05-18 21:09:07 +0000588 Decl *D = *I;
589 if (D->getLexicalDeclContext() != DC)
590 continue;
591
592 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000593
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000594 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000595 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000596 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000597 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000598
599 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000600 case RangeBefore:
601 // This declaration comes before the region of interest; skip it.
602 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000603
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000604 case RangeAfter:
605 // This declaration comes after the region of interest; we're done.
606 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000607
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000608 case RangeOverlap:
609 // This declaration overlaps the region of interest; visit it.
610 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000611 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000612 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000613
Daniel Dunbard52864b2010-02-14 10:02:57 +0000614 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000615 return true;
616 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000617
Douglas Gregorb1373d02010-01-20 20:59:29 +0000618 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000619}
620
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000621bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
622 llvm_unreachable("Translation units are visited directly by Visit()");
623 return false;
624}
625
626bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
627 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
628 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000629
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000630 return false;
631}
632
633bool CursorVisitor::VisitTagDecl(TagDecl *D) {
634 return VisitDeclContext(D);
635}
636
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000637bool CursorVisitor::VisitClassTemplateSpecializationDecl(
638 ClassTemplateSpecializationDecl *D) {
639 bool ShouldVisitBody = false;
640 switch (D->getSpecializationKind()) {
641 case TSK_Undeclared:
642 case TSK_ImplicitInstantiation:
643 // Nothing to visit
644 return false;
645
646 case TSK_ExplicitInstantiationDeclaration:
647 case TSK_ExplicitInstantiationDefinition:
648 break;
649
650 case TSK_ExplicitSpecialization:
651 ShouldVisitBody = true;
652 break;
653 }
654
655 // Visit the template arguments used in the specialization.
656 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
657 TypeLoc TL = SpecType->getTypeLoc();
658 if (TemplateSpecializationTypeLoc *TSTLoc
659 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
660 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
661 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
662 return true;
663 }
664 }
665
666 if (ShouldVisitBody && VisitCXXRecordDecl(D))
667 return true;
668
669 return false;
670}
671
Douglas Gregor74dbe642010-08-31 19:31:58 +0000672bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
673 ClassTemplatePartialSpecializationDecl *D) {
674 // FIXME: Visit the "outer" template parameter lists on the TagDecl
675 // before visiting these template parameters.
676 if (VisitTemplateParameters(D->getTemplateParameters()))
677 return true;
678
679 // Visit the partial specialization arguments.
680 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
681 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
682 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
683 return true;
684
685 return VisitCXXRecordDecl(D);
686}
687
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000688bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000689 // Visit the default argument.
690 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
691 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
692 if (Visit(DefArg->getTypeLoc()))
693 return true;
694
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000695 return false;
696}
697
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000698bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
699 if (Expr *Init = D->getInitExpr())
700 return Visit(MakeCXCursor(Init, StmtParent, TU));
701 return false;
702}
703
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000704bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
705 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
706 if (Visit(TSInfo->getTypeLoc()))
707 return true;
708
709 return false;
710}
711
Douglas Gregora67e03f2010-09-09 21:42:20 +0000712/// \brief Compare two base or member initializers based on their source order.
713static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
714 CXXBaseOrMemberInitializer const * const *X
715 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
716 CXXBaseOrMemberInitializer const * const *Y
717 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
718
719 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
720 return -1;
721 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
722 return 1;
723 else
724 return 0;
725}
726
Douglas Gregorb1373d02010-01-20 20:59:29 +0000727bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000728 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
729 // Visit the function declaration's syntactic components in the order
730 // written. This requires a bit of work.
731 TypeLoc TL = TSInfo->getTypeLoc();
732 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
733
734 // If we have a function declared directly (without the use of a typedef),
735 // visit just the return type. Otherwise, just visit the function's type
736 // now.
737 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
738 (!FTL && Visit(TL)))
739 return true;
740
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000741 // Visit the nested-name-specifier, if present.
742 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
743 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
744 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000745
746 // Visit the declaration name.
747 if (VisitDeclarationNameInfo(ND->getNameInfo()))
748 return true;
749
750 // FIXME: Visit explicitly-specified template arguments!
751
752 // Visit the function parameters, if we have a function type.
753 if (FTL && VisitFunctionTypeLoc(*FTL, true))
754 return true;
755
756 // FIXME: Attributes?
757 }
758
Douglas Gregora67e03f2010-09-09 21:42:20 +0000759 if (ND->isThisDeclarationADefinition()) {
760 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
761 // Find the initializers that were written in the source.
762 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
763 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
764 IEnd = Constructor->init_end();
765 I != IEnd; ++I) {
766 if (!(*I)->isWritten())
767 continue;
768
769 WrittenInits.push_back(*I);
770 }
771
772 // Sort the initializers in source order
773 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
774 &CompareCXXBaseOrMemberInitializers);
775
776 // Visit the initializers in source order
777 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
778 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
779 if (Init->isMemberInitializer()) {
780 if (Visit(MakeCursorMemberRef(Init->getMember(),
781 Init->getMemberLocation(), TU)))
782 return true;
783 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
784 if (Visit(BaseInfo->getTypeLoc()))
785 return true;
786 }
787
788 // Visit the initializer value.
789 if (Expr *Initializer = Init->getInit())
790 if (Visit(MakeCXCursor(Initializer, ND, TU)))
791 return true;
792 }
793 }
794
795 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
796 return true;
797 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000798
Douglas Gregorb1373d02010-01-20 20:59:29 +0000799 return false;
800}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000801
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000802bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
803 if (VisitDeclaratorDecl(D))
804 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000805
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000806 if (Expr *BitWidth = D->getBitWidth())
807 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000808
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000809 return false;
810}
811
812bool CursorVisitor::VisitVarDecl(VarDecl *D) {
813 if (VisitDeclaratorDecl(D))
814 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000815
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000816 if (Expr *Init = D->getInit())
817 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000818
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000819 return false;
820}
821
Douglas Gregor84b51d72010-09-01 20:16:53 +0000822bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
823 if (VisitDeclaratorDecl(D))
824 return true;
825
826 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
827 if (Expr *DefArg = D->getDefaultArgument())
828 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
829
830 return false;
831}
832
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000833bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
834 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
835 // before visiting these template parameters.
836 if (VisitTemplateParameters(D->getTemplateParameters()))
837 return true;
838
839 return VisitFunctionDecl(D->getTemplatedDecl());
840}
841
Douglas Gregor39d6f072010-08-31 19:02:00 +0000842bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
843 // FIXME: Visit the "outer" template parameter lists on the TagDecl
844 // before visiting these template parameters.
845 if (VisitTemplateParameters(D->getTemplateParameters()))
846 return true;
847
848 return VisitCXXRecordDecl(D->getTemplatedDecl());
849}
850
Douglas Gregor84b51d72010-09-01 20:16:53 +0000851bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
852 if (VisitTemplateParameters(D->getTemplateParameters()))
853 return true;
854
855 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
856 VisitTemplateArgumentLoc(D->getDefaultArgument()))
857 return true;
858
859 return false;
860}
861
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000862bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000863 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
864 if (Visit(TSInfo->getTypeLoc()))
865 return true;
866
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000867 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000868 PEnd = ND->param_end();
869 P != PEnd; ++P) {
870 if (Visit(MakeCXCursor(*P, TU)))
871 return true;
872 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000873
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000874 if (ND->isThisDeclarationADefinition() &&
875 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
876 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000877
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000878 return false;
879}
880
Douglas Gregora59e3902010-01-21 23:27:09 +0000881bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
882 return VisitDeclContext(D);
883}
884
Douglas Gregorb1373d02010-01-20 20:59:29 +0000885bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000886 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
887 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000888 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000889
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000890 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
891 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
892 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000893 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000894 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000895
Douglas Gregora59e3902010-01-21 23:27:09 +0000896 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000897}
898
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000899bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
900 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
901 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
902 E = PID->protocol_end(); I != E; ++I, ++PL)
903 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
904 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000905
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000906 return VisitObjCContainerDecl(PID);
907}
908
Ted Kremenek23173d72010-05-18 21:09:07 +0000909bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000910 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000911 return true;
912
Ted Kremenek23173d72010-05-18 21:09:07 +0000913 // FIXME: This implements a workaround with @property declarations also being
914 // installed in the DeclContext for the @interface. Eventually this code
915 // should be removed.
916 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
917 if (!CDecl || !CDecl->IsClassExtension())
918 return false;
919
920 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
921 if (!ID)
922 return false;
923
924 IdentifierInfo *PropertyId = PD->getIdentifier();
925 ObjCPropertyDecl *prevDecl =
926 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
927
928 if (!prevDecl)
929 return false;
930
931 // Visit synthesized methods since they will be skipped when visiting
932 // the @interface.
933 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000934 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000935 if (Visit(MakeCXCursor(MD, TU)))
936 return true;
937
938 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000939 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000940 if (Visit(MakeCXCursor(MD, TU)))
941 return true;
942
943 return false;
944}
945
Douglas Gregorb1373d02010-01-20 20:59:29 +0000946bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000947 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000948 if (D->getSuperClass() &&
949 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000950 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000951 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000952 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000953
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000954 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
955 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
956 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000957 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000958 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000959
Douglas Gregora59e3902010-01-21 23:27:09 +0000960 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000961}
962
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000963bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
964 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000965}
966
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000967bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000968 // 'ID' could be null when dealing with invalid code.
969 if (ObjCInterfaceDecl *ID = D->getClassInterface())
970 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
971 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000972
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000973 return VisitObjCImplDecl(D);
974}
975
976bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
977#if 0
978 // Issue callbacks for super class.
979 // FIXME: No source location information!
980 if (D->getSuperClass() &&
981 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000982 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000983 TU)))
984 return true;
985#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000986
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000987 return VisitObjCImplDecl(D);
988}
989
990bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
991 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
992 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
993 E = D->protocol_end();
994 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000995 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000996 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000997
998 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000999}
1000
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001001bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1002 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1003 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1004 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001005
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001006 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001007}
1008
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001009bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1010 return VisitDeclContext(D);
1011}
1012
Douglas Gregor69319002010-08-31 23:48:11 +00001013bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001014 // Visit nested-name-specifier.
1015 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1016 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1017 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001018
1019 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1020 D->getTargetNameLoc(), TU));
1021}
1022
Douglas Gregor7e242562010-09-01 19:52:22 +00001023bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001024 // Visit nested-name-specifier.
1025 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1026 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1027 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001028
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001029 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1030 return true;
1031
Douglas Gregor7e242562010-09-01 19:52:22 +00001032 return VisitDeclarationNameInfo(D->getNameInfo());
1033}
1034
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001035bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001036 // Visit nested-name-specifier.
1037 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1038 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1039 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001040
1041 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1042 D->getIdentLocation(), TU));
1043}
1044
Douglas Gregor7e242562010-09-01 19:52:22 +00001045bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001046 // Visit nested-name-specifier.
1047 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1048 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1049 return true;
1050
Douglas Gregor7e242562010-09-01 19:52:22 +00001051 return VisitDeclarationNameInfo(D->getNameInfo());
1052}
1053
1054bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1055 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001056 // Visit nested-name-specifier.
1057 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1058 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1059 return true;
1060
Douglas Gregor7e242562010-09-01 19:52:22 +00001061 return false;
1062}
1063
Douglas Gregor01829d32010-08-31 14:41:23 +00001064bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1065 switch (Name.getName().getNameKind()) {
1066 case clang::DeclarationName::Identifier:
1067 case clang::DeclarationName::CXXLiteralOperatorName:
1068 case clang::DeclarationName::CXXOperatorName:
1069 case clang::DeclarationName::CXXUsingDirective:
1070 return false;
1071
1072 case clang::DeclarationName::CXXConstructorName:
1073 case clang::DeclarationName::CXXDestructorName:
1074 case clang::DeclarationName::CXXConversionFunctionName:
1075 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1076 return Visit(TSInfo->getTypeLoc());
1077 return false;
1078
1079 case clang::DeclarationName::ObjCZeroArgSelector:
1080 case clang::DeclarationName::ObjCOneArgSelector:
1081 case clang::DeclarationName::ObjCMultiArgSelector:
1082 // FIXME: Per-identifier location info?
1083 return false;
1084 }
1085
1086 return false;
1087}
1088
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001089bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1090 SourceRange Range) {
1091 // FIXME: This whole routine is a hack to work around the lack of proper
1092 // source information in nested-name-specifiers (PR5791). Since we do have
1093 // a beginning source location, we can visit the first component of the
1094 // nested-name-specifier, if it's a single-token component.
1095 if (!NNS)
1096 return false;
1097
1098 // Get the first component in the nested-name-specifier.
1099 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1100 NNS = Prefix;
1101
1102 switch (NNS->getKind()) {
1103 case NestedNameSpecifier::Namespace:
1104 // FIXME: The token at this source location might actually have been a
1105 // namespace alias, but we don't model that. Lame!
1106 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1107 TU));
1108
1109 case NestedNameSpecifier::TypeSpec: {
1110 // If the type has a form where we know that the beginning of the source
1111 // range matches up with a reference cursor. Visit the appropriate reference
1112 // cursor.
1113 Type *T = NNS->getAsType();
1114 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1115 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1116 if (const TagType *Tag = dyn_cast<TagType>(T))
1117 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1118 if (const TemplateSpecializationType *TST
1119 = dyn_cast<TemplateSpecializationType>(T))
1120 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1121 break;
1122 }
1123
1124 case NestedNameSpecifier::TypeSpecWithTemplate:
1125 case NestedNameSpecifier::Global:
1126 case NestedNameSpecifier::Identifier:
1127 break;
1128 }
1129
1130 return false;
1131}
1132
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001133bool CursorVisitor::VisitTemplateParameters(
1134 const TemplateParameterList *Params) {
1135 if (!Params)
1136 return false;
1137
1138 for (TemplateParameterList::const_iterator P = Params->begin(),
1139 PEnd = Params->end();
1140 P != PEnd; ++P) {
1141 if (Visit(MakeCXCursor(*P, TU)))
1142 return true;
1143 }
1144
1145 return false;
1146}
1147
Douglas Gregor0b36e612010-08-31 20:37:03 +00001148bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1149 switch (Name.getKind()) {
1150 case TemplateName::Template:
1151 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1152
1153 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001154 // Visit the overloaded template set.
1155 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1156 return true;
1157
Douglas Gregor0b36e612010-08-31 20:37:03 +00001158 return false;
1159
1160 case TemplateName::DependentTemplate:
1161 // FIXME: Visit nested-name-specifier.
1162 return false;
1163
1164 case TemplateName::QualifiedTemplate:
1165 // FIXME: Visit nested-name-specifier.
1166 return Visit(MakeCursorTemplateRef(
1167 Name.getAsQualifiedTemplateName()->getDecl(),
1168 Loc, TU));
1169 }
1170
1171 return false;
1172}
1173
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001174bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1175 switch (TAL.getArgument().getKind()) {
1176 case TemplateArgument::Null:
1177 case TemplateArgument::Integral:
1178 return false;
1179
1180 case TemplateArgument::Pack:
1181 // FIXME: Implement when variadic templates come along.
1182 return false;
1183
1184 case TemplateArgument::Type:
1185 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1186 return Visit(TSInfo->getTypeLoc());
1187 return false;
1188
1189 case TemplateArgument::Declaration:
1190 if (Expr *E = TAL.getSourceDeclExpression())
1191 return Visit(MakeCXCursor(E, StmtParent, TU));
1192 return false;
1193
1194 case TemplateArgument::Expression:
1195 if (Expr *E = TAL.getSourceExpression())
1196 return Visit(MakeCXCursor(E, StmtParent, TU));
1197 return false;
1198
1199 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001200 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1201 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001202 }
1203
1204 return false;
1205}
1206
Ted Kremeneka0536d82010-05-07 01:04:29 +00001207bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1208 return VisitDeclContext(D);
1209}
1210
Douglas Gregor01829d32010-08-31 14:41:23 +00001211bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1212 return Visit(TL.getUnqualifiedLoc());
1213}
1214
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001215bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1216 ASTContext &Context = TU->getASTContext();
1217
1218 // Some builtin types (such as Objective-C's "id", "sel", and
1219 // "Class") have associated declarations. Create cursors for those.
1220 QualType VisitType;
1221 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001222 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001223 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001224 case BuiltinType::Char_U:
1225 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001226 case BuiltinType::Char16:
1227 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001228 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001229 case BuiltinType::UInt:
1230 case BuiltinType::ULong:
1231 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001232 case BuiltinType::UInt128:
1233 case BuiltinType::Char_S:
1234 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001235 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001236 case BuiltinType::Short:
1237 case BuiltinType::Int:
1238 case BuiltinType::Long:
1239 case BuiltinType::LongLong:
1240 case BuiltinType::Int128:
1241 case BuiltinType::Float:
1242 case BuiltinType::Double:
1243 case BuiltinType::LongDouble:
1244 case BuiltinType::NullPtr:
1245 case BuiltinType::Overload:
1246 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001247 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001248
1249 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001250 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001251
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001252 case BuiltinType::ObjCId:
1253 VisitType = Context.getObjCIdType();
1254 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001255
1256 case BuiltinType::ObjCClass:
1257 VisitType = Context.getObjCClassType();
1258 break;
1259
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001260 case BuiltinType::ObjCSel:
1261 VisitType = Context.getObjCSelType();
1262 break;
1263 }
1264
1265 if (!VisitType.isNull()) {
1266 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001267 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001268 TU));
1269 }
1270
1271 return false;
1272}
1273
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001274bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1275 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1276}
1277
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001278bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1279 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1280}
1281
1282bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1283 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1284}
1285
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001286bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001287 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001288 // no context information with which we can match up the depth/index in the
1289 // type to the appropriate
1290 return false;
1291}
1292
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001293bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1294 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1295 return true;
1296
John McCallc12c5bb2010-05-15 11:32:37 +00001297 return false;
1298}
1299
1300bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1301 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1302 return true;
1303
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001304 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1305 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1306 TU)))
1307 return true;
1308 }
1309
1310 return false;
1311}
1312
1313bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001314 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001315}
1316
1317bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1318 return Visit(TL.getPointeeLoc());
1319}
1320
1321bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1322 return Visit(TL.getPointeeLoc());
1323}
1324
1325bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1326 return Visit(TL.getPointeeLoc());
1327}
1328
1329bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001330 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001331}
1332
1333bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001334 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001335}
1336
Douglas Gregor01829d32010-08-31 14:41:23 +00001337bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1338 bool SkipResultType) {
1339 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001340 return true;
1341
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001342 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001343 if (Decl *D = TL.getArg(I))
1344 if (Visit(MakeCXCursor(D, TU)))
1345 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001346
1347 return false;
1348}
1349
1350bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1351 if (Visit(TL.getElementLoc()))
1352 return true;
1353
1354 if (Expr *Size = TL.getSizeExpr())
1355 return Visit(MakeCXCursor(Size, StmtParent, TU));
1356
1357 return false;
1358}
1359
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001360bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1361 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001362 // Visit the template name.
1363 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1364 TL.getTemplateNameLoc()))
1365 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001366
1367 // Visit the template arguments.
1368 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1369 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1370 return true;
1371
1372 return false;
1373}
1374
Douglas Gregor2332c112010-01-21 20:48:56 +00001375bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1376 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1377}
1378
1379bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1380 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1381 return Visit(TSInfo->getTypeLoc());
1382
1383 return false;
1384}
1385
Douglas Gregora59e3902010-01-21 23:27:09 +00001386bool CursorVisitor::VisitStmt(Stmt *S) {
1387 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1388 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001389 if (Stmt *C = *Child)
1390 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1391 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001392 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001393
Douglas Gregora59e3902010-01-21 23:27:09 +00001394 return false;
1395}
1396
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001397bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1398 // Specially handle CaseStmts because they can be nested, e.g.:
1399 //
1400 // case 1:
1401 // case 2:
1402 //
1403 // In this case the second CaseStmt is the child of the first. Walking
1404 // these recursively can blow out the stack.
1405 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1406 while (true) {
1407 // Set the Parent field to Cursor, then back to its old value once we're
1408 // done.
1409 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1410
1411 if (Stmt *LHS = S->getLHS())
1412 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1413 return true;
1414 if (Stmt *RHS = S->getRHS())
1415 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1416 return true;
1417 if (Stmt *SubStmt = S->getSubStmt()) {
1418 if (!isa<CaseStmt>(SubStmt))
1419 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1420
1421 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1422 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1423 Cursor = MakeCXCursor(CS, StmtParent, TU);
1424 if (RegionOfInterest.isValid()) {
1425 SourceRange Range = CS->getSourceRange();
1426 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1427 return false;
1428 }
1429
1430 switch (Visitor(Cursor, Parent, ClientData)) {
1431 case CXChildVisit_Break: return true;
1432 case CXChildVisit_Continue: return false;
1433 case CXChildVisit_Recurse:
1434 // Perform tail-recursion manually.
1435 S = CS;
1436 continue;
1437 }
1438 }
1439 return false;
1440 }
1441}
1442
Douglas Gregora59e3902010-01-21 23:27:09 +00001443bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1444 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1445 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001446 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001447 return true;
1448 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001449
Douglas Gregora59e3902010-01-21 23:27:09 +00001450 return false;
1451}
1452
Douglas Gregor36897b02010-09-10 00:22:18 +00001453bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1454 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1455}
1456
Douglas Gregorf5bab412010-01-22 01:00:11 +00001457bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1458 if (VarDecl *Var = S->getConditionVariable()) {
1459 if (Visit(MakeCXCursor(Var, TU)))
1460 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001461 }
1462
Douglas Gregor263b47b2010-01-25 16:12:32 +00001463 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1464 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001465 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1466 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001467 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1468 return true;
1469
1470 return false;
1471}
1472
1473bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1474 if (VarDecl *Var = S->getConditionVariable()) {
1475 if (Visit(MakeCXCursor(Var, TU)))
1476 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001477 }
1478
Douglas Gregor263b47b2010-01-25 16:12:32 +00001479 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1480 return true;
1481 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1482 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001483
Douglas Gregor263b47b2010-01-25 16:12:32 +00001484 return false;
1485}
1486
1487bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1488 if (VarDecl *Var = S->getConditionVariable()) {
1489 if (Visit(MakeCXCursor(Var, TU)))
1490 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001491 }
1492
Douglas Gregor263b47b2010-01-25 16:12:32 +00001493 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1494 return true;
1495 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001496 return true;
1497
Douglas Gregor263b47b2010-01-25 16:12:32 +00001498 return false;
1499}
1500
1501bool CursorVisitor::VisitForStmt(ForStmt *S) {
1502 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1503 return true;
1504 if (VarDecl *Var = S->getConditionVariable()) {
1505 if (Visit(MakeCXCursor(Var, TU)))
1506 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001507 }
1508
Douglas Gregor263b47b2010-01-25 16:12:32 +00001509 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1510 return true;
1511 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1512 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001513 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1514 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001515
Douglas Gregorf5bab412010-01-22 01:00:11 +00001516 return false;
1517}
1518
Douglas Gregor8947a752010-09-02 20:35:02 +00001519bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1520 // Visit nested-name-specifier, if present.
1521 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1522 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1523 return true;
1524
1525 // Visit declaration name.
1526 if (VisitDeclarationNameInfo(E->getNameInfo()))
1527 return true;
1528
1529 // Visit explicitly-specified template arguments.
1530 if (E->hasExplicitTemplateArgs()) {
1531 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1532 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1533 *ArgEnd = Arg + Args.NumTemplateArgs;
1534 Arg != ArgEnd; ++Arg)
1535 if (VisitTemplateArgumentLoc(*Arg))
1536 return true;
1537 }
1538
1539 return false;
1540}
1541
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001542bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1543 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1544 return true;
1545
1546 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1547 return true;
1548
1549 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1550 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1551 return true;
1552
1553 return false;
1554}
1555
Ted Kremenek3064ef92010-08-27 21:34:58 +00001556bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1557 if (D->isDefinition()) {
1558 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1559 E = D->bases_end(); I != E; ++I) {
1560 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1561 return true;
1562 }
1563 }
1564
1565 return VisitTagDecl(D);
1566}
1567
1568
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001569bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1570 return Visit(B->getBlockDecl());
1571}
1572
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001573bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001574 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001575 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1576 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001577
1578 // Visit the components of the offsetof expression.
1579 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1580 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1581 const OffsetOfNode &Node = E->getComponent(I);
1582 switch (Node.getKind()) {
1583 case OffsetOfNode::Array:
1584 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1585 StmtParent, TU)))
1586 return true;
1587 break;
1588
1589 case OffsetOfNode::Field:
1590 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1591 TU)))
1592 return true;
1593 break;
1594
1595 case OffsetOfNode::Identifier:
1596 case OffsetOfNode::Base:
1597 continue;
1598 }
1599 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001600
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001601 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001602}
1603
Douglas Gregor336fd812010-01-23 00:40:08 +00001604bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1605 if (E->isArgumentType()) {
1606 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1607 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001608
Douglas Gregor336fd812010-01-23 00:40:08 +00001609 return false;
1610 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001611
Douglas Gregor336fd812010-01-23 00:40:08 +00001612 return VisitExpr(E);
1613}
1614
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001615bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1616 // Visit the base expression.
1617 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1618 return true;
1619
1620 // Visit the nested-name-specifier
1621 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1622 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1623 return true;
1624
1625 // Visit the declaration name.
1626 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1627 return true;
1628
1629 // Visit the explicitly-specified template arguments, if any.
1630 if (E->hasExplicitTemplateArgs()) {
1631 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1632 *ArgEnd = Arg + E->getNumTemplateArgs();
1633 Arg != ArgEnd;
1634 ++Arg) {
1635 if (VisitTemplateArgumentLoc(*Arg))
1636 return true;
1637 }
1638 }
1639
1640 return false;
1641}
1642
Douglas Gregor336fd812010-01-23 00:40:08 +00001643bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1644 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1645 if (Visit(TSInfo->getTypeLoc()))
1646 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001647
Douglas Gregor336fd812010-01-23 00:40:08 +00001648 return VisitCastExpr(E);
1649}
1650
1651bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1652 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1653 if (Visit(TSInfo->getTypeLoc()))
1654 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001655
Douglas Gregor336fd812010-01-23 00:40:08 +00001656 return VisitExpr(E);
1657}
1658
Douglas Gregor36897b02010-09-10 00:22:18 +00001659bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1660 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1661}
1662
Douglas Gregor648220e2010-08-10 15:02:34 +00001663bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1664 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1665 Visit(E->getArgTInfo2()->getTypeLoc());
1666}
1667
1668bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1669 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1670 return true;
1671
1672 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1673}
1674
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001675bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1676 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001677 if (InitListExpr *Syntactic = E->getSyntacticForm())
1678 return VisitExpr(Syntactic);
1679
1680 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001681}
1682
1683bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1684 // Visit the designators.
1685 typedef DesignatedInitExpr::Designator Designator;
1686 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1687 DEnd = E->designators_end();
1688 D != DEnd; ++D) {
1689 if (D->isFieldDesignator()) {
1690 if (FieldDecl *Field = D->getField())
1691 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1692 return true;
1693
1694 continue;
1695 }
1696
1697 if (D->isArrayDesignator()) {
1698 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1699 return true;
1700
1701 continue;
1702 }
1703
1704 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1705 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1706 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1707 return true;
1708 }
1709
1710 // Visit the initializer value itself.
1711 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1712}
1713
Douglas Gregor94802292010-09-02 21:20:16 +00001714bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1715 if (E->isTypeOperand()) {
1716 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1717 return Visit(TSInfo->getTypeLoc());
1718
1719 return false;
1720 }
1721
1722 return VisitExpr(E);
1723}
1724
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001725bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1726 if (E->isTypeOperand()) {
1727 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1728 return Visit(TSInfo->getTypeLoc());
1729
1730 return false;
1731 }
1732
1733 return VisitExpr(E);
1734}
1735
Douglas Gregorab6677e2010-09-08 00:15:04 +00001736bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1737 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1738 return Visit(TSInfo->getTypeLoc());
1739
1740 return VisitExpr(E);
1741}
1742
1743bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1744 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1745 return Visit(TSInfo->getTypeLoc());
1746
1747 return false;
1748}
1749
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001750bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1751 // Visit placement arguments.
1752 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1753 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1754 return true;
1755
1756 // Visit the allocated type.
1757 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1758 if (Visit(TSInfo->getTypeLoc()))
1759 return true;
1760
1761 // Visit the array size, if any.
1762 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1763 return true;
1764
1765 // Visit the initializer or constructor arguments.
1766 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1767 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1768 return true;
1769
1770 return false;
1771}
1772
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001773bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1774 // Visit base expression.
1775 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1776 return true;
1777
1778 // Visit the nested-name-specifier.
1779 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1780 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1781 return true;
1782
1783 // Visit the scope type that looks disturbingly like the nested-name-specifier
1784 // but isn't.
1785 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1786 if (Visit(TSInfo->getTypeLoc()))
1787 return true;
1788
1789 // Visit the name of the type being destroyed.
1790 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1791 if (Visit(TSInfo->getTypeLoc()))
1792 return true;
1793
1794 return false;
1795}
1796
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001797bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1798 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1799}
1800
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001801bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001802 // Visit the nested-name-specifier.
1803 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1804 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1805 return true;
1806
1807 // Visit the declaration name.
1808 if (VisitDeclarationNameInfo(E->getNameInfo()))
1809 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001810
1811 // Visit the overloaded declaration reference.
1812 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1813 return true;
1814
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001815 // Visit the explicitly-specified template arguments.
1816 if (const ExplicitTemplateArgumentList *ArgList
1817 = E->getOptionalExplicitTemplateArgs()) {
1818 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1819 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1820 Arg != ArgEnd; ++Arg) {
1821 if (VisitTemplateArgumentLoc(*Arg))
1822 return true;
1823 }
1824 }
1825
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001826 return false;
1827}
1828
Douglas Gregorbfebed22010-09-03 17:24:10 +00001829bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1830 DependentScopeDeclRefExpr *E) {
1831 // Visit the nested-name-specifier.
1832 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1833 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1834 return true;
1835
1836 // Visit the declaration name.
1837 if (VisitDeclarationNameInfo(E->getNameInfo()))
1838 return true;
1839
1840 // Visit the explicitly-specified template arguments.
1841 if (const ExplicitTemplateArgumentList *ArgList
1842 = E->getOptionalExplicitTemplateArgs()) {
1843 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1844 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1845 Arg != ArgEnd; ++Arg) {
1846 if (VisitTemplateArgumentLoc(*Arg))
1847 return true;
1848 }
1849 }
1850
1851 return false;
1852}
1853
Douglas Gregorab6677e2010-09-08 00:15:04 +00001854bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1855 CXXUnresolvedConstructExpr *E) {
1856 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1857 if (Visit(TSInfo->getTypeLoc()))
1858 return true;
1859
1860 return VisitExpr(E);
1861}
1862
Douglas Gregor25d63622010-09-03 17:35:34 +00001863bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1864 CXXDependentScopeMemberExpr *E) {
1865 // Visit the base expression, if there is one.
1866 if (!E->isImplicitAccess() &&
1867 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1868 return true;
1869
1870 // Visit the nested-name-specifier.
1871 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1872 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1873 return true;
1874
1875 // Visit the declaration name.
1876 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1877 return true;
1878
1879 // Visit the explicitly-specified template arguments.
1880 if (const ExplicitTemplateArgumentList *ArgList
1881 = E->getOptionalExplicitTemplateArgs()) {
1882 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1883 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1884 Arg != ArgEnd; ++Arg) {
1885 if (VisitTemplateArgumentLoc(*Arg))
1886 return true;
1887 }
1888 }
1889
1890 return false;
1891}
1892
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001893bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1894 // Visit the base expression, if there is one.
1895 if (!E->isImplicitAccess() &&
1896 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1897 return true;
1898
1899 return VisitOverloadExpr(E);
1900}
Douglas Gregor25d63622010-09-03 17:35:34 +00001901
Douglas Gregorc2350e52010-03-08 16:40:19 +00001902bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001903 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1904 if (Visit(TSInfo->getTypeLoc()))
1905 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001906
1907 return VisitExpr(E);
1908}
1909
Douglas Gregor81d34662010-04-20 15:39:42 +00001910bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1911 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1912}
1913
1914
Ted Kremenek09dfa372010-02-18 05:46:33 +00001915bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001916 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1917 i != e; ++i)
1918 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001919 return true;
1920
1921 return false;
1922}
1923
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001924static llvm::sys::Mutex EnableMultithreadingMutex;
1925static bool EnabledMultithreading;
1926
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001927extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001928CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1929 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00001930 // Disable pretty stack trace functionality, which will otherwise be a very
1931 // poor citizen of the world and set up all sorts of signal handlers.
1932 llvm::DisablePrettyStackTrace = true;
1933
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001934 // We use crash recovery to make some of our APIs more reliable, implicitly
1935 // enable it.
1936 llvm::CrashRecoveryContext::Enable();
1937
Douglas Gregor8c8d5412010-09-24 21:18:36 +00001938 // Enable support for multithreading in LLVM.
1939 {
1940 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
1941 if (!EnabledMultithreading) {
1942 llvm::llvm_start_multithreaded();
1943 EnabledMultithreading = true;
1944 }
1945 }
1946
Douglas Gregora030b7c2010-01-22 20:35:53 +00001947 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001948 if (excludeDeclarationsFromPCH)
1949 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001950 if (displayDiagnostics)
1951 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001952 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001953}
1954
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001955void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001956 if (CIdx)
1957 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001958}
1959
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001960CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001961 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001962 if (!CIdx)
1963 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001964
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001965 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001966
Douglas Gregor28019772010-04-05 23:52:57 +00001967 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001968 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001969 CXXIdx->getOnlyLocalDecls(),
1970 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001971}
1972
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001973unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00001974 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00001975 CXTranslationUnit_CacheCompletionResults |
1976 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001977}
1978
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001979CXTranslationUnit
1980clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1981 const char *source_filename,
1982 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001983 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001984 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001985 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001986 return clang_parseTranslationUnit(CIdx, source_filename,
1987 command_line_args, num_command_line_args,
1988 unsaved_files, num_unsaved_files,
1989 CXTranslationUnit_DetailedPreprocessingRecord);
1990}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001991
1992struct ParseTranslationUnitInfo {
1993 CXIndex CIdx;
1994 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001995 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001996 int num_command_line_args;
1997 struct CXUnsavedFile *unsaved_files;
1998 unsigned num_unsaved_files;
1999 unsigned options;
2000 CXTranslationUnit result;
2001};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002002static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002003 ParseTranslationUnitInfo *PTUI =
2004 static_cast<ParseTranslationUnitInfo*>(UserData);
2005 CXIndex CIdx = PTUI->CIdx;
2006 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002007 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002008 int num_command_line_args = PTUI->num_command_line_args;
2009 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2010 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2011 unsigned options = PTUI->options;
2012 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002013
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002014 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002015 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002016
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002017 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2018
Douglas Gregor44c181a2010-07-23 00:33:23 +00002019 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002020 bool CompleteTranslationUnit
2021 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002022 bool CacheCodeCompetionResults
2023 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002024 bool CXXPrecompilePreamble
2025 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2026 bool CXXChainedPCH
2027 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002028
Douglas Gregor5352ac02010-01-28 00:27:43 +00002029 // Configure the diagnostics.
2030 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002031 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2032 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002033
Douglas Gregor4db64a42010-01-23 00:14:00 +00002034 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2035 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002036 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002037 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002038 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002039 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2040 Buffer));
2041 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002042
Douglas Gregorb10daed2010-10-11 16:52:23 +00002043 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002044
Ted Kremenek139ba862009-10-22 00:03:57 +00002045 // The 'source_filename' argument is optional. If the caller does not
2046 // specify it then it is assumed that the source file is specified
2047 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002048 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002049 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002050
2051 // Since the Clang C library is primarily used by batch tools dealing with
2052 // (often very broken) source code, where spell-checking can have a
2053 // significant negative impact on performance (particularly when
2054 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002055 // Only do this if we haven't found a spell-checking-related argument.
2056 bool FoundSpellCheckingArgument = false;
2057 for (int I = 0; I != num_command_line_args; ++I) {
2058 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2059 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2060 FoundSpellCheckingArgument = true;
2061 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002062 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002063 }
2064 if (!FoundSpellCheckingArgument)
2065 Args.push_back("-fno-spell-checking");
2066
2067 Args.insert(Args.end(), command_line_args,
2068 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002069
Douglas Gregor44c181a2010-07-23 00:33:23 +00002070 // Do we need the detailed preprocessing record?
2071 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002072 Args.push_back("-Xclang");
2073 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002074 }
2075
Douglas Gregorb10daed2010-10-11 16:52:23 +00002076 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenek74cd0692009-10-15 23:21:22 +00002077
Douglas Gregorb10daed2010-10-11 16:52:23 +00002078#ifdef USE_CRASHTRACER
2079 ArgsCrashTracerInfo ACTI(Args);
2080#endif
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002081
Douglas Gregorb10daed2010-10-11 16:52:23 +00002082 llvm::OwningPtr<ASTUnit> Unit(
2083 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2084 Diags,
2085 CXXIdx->getClangResourcesPath(),
2086 CXXIdx->getOnlyLocalDecls(),
2087 RemappedFiles.data(),
2088 RemappedFiles.size(),
2089 /*CaptureDiagnostics=*/true,
2090 PrecompilePreamble,
2091 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002092 CacheCodeCompetionResults,
2093 CXXPrecompilePreamble,
2094 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002095
Douglas Gregorb10daed2010-10-11 16:52:23 +00002096 if (NumErrors != Diags->getNumErrors()) {
2097 // Make sure to check that 'Unit' is non-NULL.
2098 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2099 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2100 DEnd = Unit->stored_diag_end();
2101 D != DEnd; ++D) {
2102 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2103 CXString Msg = clang_formatDiagnostic(&Diag,
2104 clang_defaultDiagnosticDisplayOptions());
2105 fprintf(stderr, "%s\n", clang_getCString(Msg));
2106 clang_disposeString(Msg);
2107 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002108#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002109 // On Windows, force a flush, since there may be multiple copies of
2110 // stderr and stdout in the file system, all with different buffers
2111 // but writing to the same device.
2112 fflush(stderr);
2113#endif
2114 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002115 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002116
Douglas Gregorb10daed2010-10-11 16:52:23 +00002117 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002118}
2119CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2120 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002121 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002122 int num_command_line_args,
2123 struct CXUnsavedFile *unsaved_files,
2124 unsigned num_unsaved_files,
2125 unsigned options) {
2126 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2127 num_command_line_args, unsaved_files, num_unsaved_files,
2128 options, 0 };
2129 llvm::CrashRecoveryContext CRC;
2130
2131 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002132 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2133 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2134 fprintf(stderr, " 'command_line_args' : [");
2135 for (int i = 0; i != num_command_line_args; ++i) {
2136 if (i)
2137 fprintf(stderr, ", ");
2138 fprintf(stderr, "'%s'", command_line_args[i]);
2139 }
2140 fprintf(stderr, "],\n");
2141 fprintf(stderr, " 'unsaved_files' : [");
2142 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2143 if (i)
2144 fprintf(stderr, ", ");
2145 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2146 unsaved_files[i].Length);
2147 }
2148 fprintf(stderr, "],\n");
2149 fprintf(stderr, " 'options' : %d,\n", options);
2150 fprintf(stderr, "}\n");
2151
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002152 return 0;
2153 }
2154
2155 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002156}
2157
Douglas Gregor19998442010-08-13 15:35:05 +00002158unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2159 return CXSaveTranslationUnit_None;
2160}
2161
2162int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2163 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002164 if (!TU)
2165 return 1;
2166
2167 return static_cast<ASTUnit *>(TU)->Save(FileName);
2168}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002169
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002170void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002171 if (CTUnit) {
2172 // If the translation unit has been marked as unsafe to free, just discard
2173 // it.
2174 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2175 return;
2176
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002177 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002178 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002179}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002180
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002181unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2182 return CXReparse_None;
2183}
2184
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002185struct ReparseTranslationUnitInfo {
2186 CXTranslationUnit TU;
2187 unsigned num_unsaved_files;
2188 struct CXUnsavedFile *unsaved_files;
2189 unsigned options;
2190 int result;
2191};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002192
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002193static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002194 ReparseTranslationUnitInfo *RTUI =
2195 static_cast<ReparseTranslationUnitInfo*>(UserData);
2196 CXTranslationUnit TU = RTUI->TU;
2197 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2198 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2199 unsigned options = RTUI->options;
2200 (void) options;
2201 RTUI->result = 1;
2202
Douglas Gregorabc563f2010-07-19 21:46:24 +00002203 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002204 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002205
2206 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2207 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002208
2209 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2210 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2211 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2212 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002213 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002214 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2215 Buffer));
2216 }
2217
Douglas Gregor593b0c12010-09-23 18:47:53 +00002218 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2219 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002220}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002221
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002222int clang_reparseTranslationUnit(CXTranslationUnit TU,
2223 unsigned num_unsaved_files,
2224 struct CXUnsavedFile *unsaved_files,
2225 unsigned options) {
2226 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2227 options, 0 };
2228 llvm::CrashRecoveryContext CRC;
2229
2230 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002231 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002232 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2233 return 1;
2234 }
2235
2236 return RTUI.result;
2237}
2238
Douglas Gregordf95a132010-08-09 20:45:32 +00002239
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002240CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002241 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002242 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002243
Steve Naroff77accc12009-09-03 18:19:54 +00002244 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002245 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002246}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002247
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002248CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002249 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002250 return Result;
2251}
2252
Ted Kremenekfb480492010-01-13 21:46:36 +00002253} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002254
Ted Kremenekfb480492010-01-13 21:46:36 +00002255//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002256// CXSourceLocation and CXSourceRange Operations.
2257//===----------------------------------------------------------------------===//
2258
Douglas Gregorb9790342010-01-22 21:44:22 +00002259extern "C" {
2260CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002261 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002262 return Result;
2263}
2264
2265unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002266 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2267 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2268 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002269}
2270
2271CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2272 CXFile file,
2273 unsigned line,
2274 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002275 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002276 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002277
Douglas Gregorb9790342010-01-22 21:44:22 +00002278 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2279 SourceLocation SLoc
2280 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002281 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002282 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002283 if (SLoc.isInvalid()) return clang_getNullLocation();
2284
2285 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2286}
2287
2288CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2289 CXFile file,
2290 unsigned offset) {
2291 if (!tu || !file)
2292 return clang_getNullLocation();
2293
2294 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2295 SourceLocation Start
2296 = CXXUnit->getSourceManager().getLocation(
2297 static_cast<const FileEntry *>(file),
2298 1, 1);
2299 if (Start.isInvalid()) return clang_getNullLocation();
2300
2301 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2302
2303 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002304
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002305 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002306}
2307
Douglas Gregor5352ac02010-01-28 00:27:43 +00002308CXSourceRange clang_getNullRange() {
2309 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2310 return Result;
2311}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002312
Douglas Gregor5352ac02010-01-28 00:27:43 +00002313CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2314 if (begin.ptr_data[0] != end.ptr_data[0] ||
2315 begin.ptr_data[1] != end.ptr_data[1])
2316 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002317
2318 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002319 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002320 return Result;
2321}
2322
Douglas Gregor46766dc2010-01-26 19:19:08 +00002323void clang_getInstantiationLocation(CXSourceLocation location,
2324 CXFile *file,
2325 unsigned *line,
2326 unsigned *column,
2327 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002328 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2329
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002330 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002331 if (file)
2332 *file = 0;
2333 if (line)
2334 *line = 0;
2335 if (column)
2336 *column = 0;
2337 if (offset)
2338 *offset = 0;
2339 return;
2340 }
2341
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002342 const SourceManager &SM =
2343 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002344 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002345
2346 if (file)
2347 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2348 if (line)
2349 *line = SM.getInstantiationLineNumber(InstLoc);
2350 if (column)
2351 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002352 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002353 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002354}
2355
Douglas Gregor1db19de2010-01-19 21:36:55 +00002356CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002357 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002358 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002359 return Result;
2360}
2361
2362CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002363 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002364 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002365 return Result;
2366}
2367
Douglas Gregorb9790342010-01-22 21:44:22 +00002368} // end: extern "C"
2369
Douglas Gregor1db19de2010-01-19 21:36:55 +00002370//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002371// CXFile Operations.
2372//===----------------------------------------------------------------------===//
2373
2374extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002375CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002376 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002377 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002378
Steve Naroff88145032009-10-27 14:35:18 +00002379 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002380 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002381}
2382
2383time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002384 if (!SFile)
2385 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002386
Steve Naroff88145032009-10-27 14:35:18 +00002387 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2388 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002389}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002390
Douglas Gregorb9790342010-01-22 21:44:22 +00002391CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2392 if (!tu)
2393 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002394
Douglas Gregorb9790342010-01-22 21:44:22 +00002395 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002396
Douglas Gregorb9790342010-01-22 21:44:22 +00002397 FileManager &FMgr = CXXUnit->getFileManager();
2398 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2399 return const_cast<FileEntry *>(File);
2400}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002401
Ted Kremenekfb480492010-01-13 21:46:36 +00002402} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002403
Ted Kremenekfb480492010-01-13 21:46:36 +00002404//===----------------------------------------------------------------------===//
2405// CXCursor Operations.
2406//===----------------------------------------------------------------------===//
2407
Ted Kremenekfb480492010-01-13 21:46:36 +00002408static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002409 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2410 return getDeclFromExpr(CE->getSubExpr());
2411
Ted Kremenekfb480492010-01-13 21:46:36 +00002412 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2413 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002414 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2415 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002416 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2417 return ME->getMemberDecl();
2418 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2419 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002420 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2421 return PRE->getProperty();
2422
Ted Kremenekfb480492010-01-13 21:46:36 +00002423 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2424 return getDeclFromExpr(CE->getCallee());
Ted Kremenekfb480492010-01-13 21:46:36 +00002425 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2426 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002427
Douglas Gregordb1314e2010-10-01 21:11:22 +00002428 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2429 return PE->getProtocol();
2430
Ted Kremenekfb480492010-01-13 21:46:36 +00002431 return 0;
2432}
2433
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002434static SourceLocation getLocationFromExpr(Expr *E) {
2435 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2436 return /*FIXME:*/Msg->getLeftLoc();
2437 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2438 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002439 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2440 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002441 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2442 return Member->getMemberLoc();
2443 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2444 return Ivar->getLocation();
2445 return E->getLocStart();
2446}
2447
Ted Kremenekfb480492010-01-13 21:46:36 +00002448extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002449
2450unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002451 CXCursorVisitor visitor,
2452 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002453 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002454
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002455 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2456 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002457 return CursorVis.VisitChildren(parent);
2458}
2459
Douglas Gregor78205d42010-01-20 21:45:58 +00002460static CXString getDeclSpelling(Decl *D) {
2461 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2462 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002463 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002464
Douglas Gregor78205d42010-01-20 21:45:58 +00002465 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002466 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002467
Douglas Gregor78205d42010-01-20 21:45:58 +00002468 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2469 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2470 // and returns different names. NamedDecl returns the class name and
2471 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002472 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002473
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002474 if (isa<UsingDirectiveDecl>(D))
2475 return createCXString("");
2476
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002477 llvm::SmallString<1024> S;
2478 llvm::raw_svector_ostream os(S);
2479 ND->printName(os);
2480
2481 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002482}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002483
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002484CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002485 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002486 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002487
Steve Narofff334b4e2009-09-02 18:26:48 +00002488 if (clang_isReference(C.kind)) {
2489 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002490 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002491 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002492 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002493 }
2494 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002495 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002496 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002497 }
2498 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002499 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002500 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002501 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002502 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002503 case CXCursor_CXXBaseSpecifier: {
2504 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2505 return createCXString(B->getType().getAsString());
2506 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002507 case CXCursor_TypeRef: {
2508 TypeDecl *Type = getCursorTypeRef(C).first;
2509 assert(Type && "Missing type decl");
2510
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002511 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2512 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002513 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002514 case CXCursor_TemplateRef: {
2515 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002516 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002517
2518 return createCXString(Template->getNameAsString());
2519 }
Douglas Gregor69319002010-08-31 23:48:11 +00002520
2521 case CXCursor_NamespaceRef: {
2522 NamedDecl *NS = getCursorNamespaceRef(C).first;
2523 assert(NS && "Missing namespace decl");
2524
2525 return createCXString(NS->getNameAsString());
2526 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002527
Douglas Gregora67e03f2010-09-09 21:42:20 +00002528 case CXCursor_MemberRef: {
2529 FieldDecl *Field = getCursorMemberRef(C).first;
2530 assert(Field && "Missing member decl");
2531
2532 return createCXString(Field->getNameAsString());
2533 }
2534
Douglas Gregor36897b02010-09-10 00:22:18 +00002535 case CXCursor_LabelRef: {
2536 LabelStmt *Label = getCursorLabelRef(C).first;
2537 assert(Label && "Missing label");
2538
2539 return createCXString(Label->getID()->getName());
2540 }
2541
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002542 case CXCursor_OverloadedDeclRef: {
2543 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2544 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2545 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2546 return createCXString(ND->getNameAsString());
2547 return createCXString("");
2548 }
2549 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2550 return createCXString(E->getName().getAsString());
2551 OverloadedTemplateStorage *Ovl
2552 = Storage.get<OverloadedTemplateStorage*>();
2553 if (Ovl->size() == 0)
2554 return createCXString("");
2555 return createCXString((*Ovl->begin())->getNameAsString());
2556 }
2557
Daniel Dunbaracca7252009-11-30 20:42:49 +00002558 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002559 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002560 }
2561 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002562
2563 if (clang_isExpression(C.kind)) {
2564 Decl *D = getDeclFromExpr(getCursorExpr(C));
2565 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002566 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002567 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002568 }
2569
Douglas Gregor36897b02010-09-10 00:22:18 +00002570 if (clang_isStatement(C.kind)) {
2571 Stmt *S = getCursorStmt(C);
2572 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2573 return createCXString(Label->getID()->getName());
2574
2575 return createCXString("");
2576 }
2577
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002578 if (C.kind == CXCursor_MacroInstantiation)
2579 return createCXString(getCursorMacroInstantiation(C)->getName()
2580 ->getNameStart());
2581
Douglas Gregor572feb22010-03-18 18:04:21 +00002582 if (C.kind == CXCursor_MacroDefinition)
2583 return createCXString(getCursorMacroDefinition(C)->getName()
2584 ->getNameStart());
2585
Douglas Gregorecdcb882010-10-20 22:00:55 +00002586 if (C.kind == CXCursor_InclusionDirective)
2587 return createCXString(getCursorInclusionDirective(C)->getFileName());
2588
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002589 if (clang_isDeclaration(C.kind))
2590 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002591
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002592 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002593}
2594
Douglas Gregor358559d2010-10-02 22:49:11 +00002595CXString clang_getCursorDisplayName(CXCursor C) {
2596 if (!clang_isDeclaration(C.kind))
2597 return clang_getCursorSpelling(C);
2598
2599 Decl *D = getCursorDecl(C);
2600 if (!D)
2601 return createCXString("");
2602
2603 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2604 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2605 D = FunTmpl->getTemplatedDecl();
2606
2607 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2608 llvm::SmallString<64> Str;
2609 llvm::raw_svector_ostream OS(Str);
2610 OS << Function->getNameAsString();
2611 if (Function->getPrimaryTemplate())
2612 OS << "<>";
2613 OS << "(";
2614 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2615 if (I)
2616 OS << ", ";
2617 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2618 }
2619
2620 if (Function->isVariadic()) {
2621 if (Function->getNumParams())
2622 OS << ", ";
2623 OS << "...";
2624 }
2625 OS << ")";
2626 return createCXString(OS.str());
2627 }
2628
2629 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2630 llvm::SmallString<64> Str;
2631 llvm::raw_svector_ostream OS(Str);
2632 OS << ClassTemplate->getNameAsString();
2633 OS << "<";
2634 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2635 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2636 if (I)
2637 OS << ", ";
2638
2639 NamedDecl *Param = Params->getParam(I);
2640 if (Param->getIdentifier()) {
2641 OS << Param->getIdentifier()->getName();
2642 continue;
2643 }
2644
2645 // There is no parameter name, which makes this tricky. Try to come up
2646 // with something useful that isn't too long.
2647 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2648 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2649 else if (NonTypeTemplateParmDecl *NTTP
2650 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2651 OS << NTTP->getType().getAsString(Policy);
2652 else
2653 OS << "template<...> class";
2654 }
2655
2656 OS << ">";
2657 return createCXString(OS.str());
2658 }
2659
2660 if (ClassTemplateSpecializationDecl *ClassSpec
2661 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2662 // If the type was explicitly written, use that.
2663 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2664 return createCXString(TSInfo->getType().getAsString(Policy));
2665
2666 llvm::SmallString<64> Str;
2667 llvm::raw_svector_ostream OS(Str);
2668 OS << ClassSpec->getNameAsString();
2669 OS << TemplateSpecializationType::PrintTemplateArgumentList(
2670 ClassSpec->getTemplateArgs().getFlatArgumentList(),
2671 ClassSpec->getTemplateArgs().flat_size(),
2672 Policy);
2673 return createCXString(OS.str());
2674 }
2675
2676 return clang_getCursorSpelling(C);
2677}
2678
Ted Kremeneke68fff62010-02-17 00:41:32 +00002679CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002680 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002681 case CXCursor_FunctionDecl:
2682 return createCXString("FunctionDecl");
2683 case CXCursor_TypedefDecl:
2684 return createCXString("TypedefDecl");
2685 case CXCursor_EnumDecl:
2686 return createCXString("EnumDecl");
2687 case CXCursor_EnumConstantDecl:
2688 return createCXString("EnumConstantDecl");
2689 case CXCursor_StructDecl:
2690 return createCXString("StructDecl");
2691 case CXCursor_UnionDecl:
2692 return createCXString("UnionDecl");
2693 case CXCursor_ClassDecl:
2694 return createCXString("ClassDecl");
2695 case CXCursor_FieldDecl:
2696 return createCXString("FieldDecl");
2697 case CXCursor_VarDecl:
2698 return createCXString("VarDecl");
2699 case CXCursor_ParmDecl:
2700 return createCXString("ParmDecl");
2701 case CXCursor_ObjCInterfaceDecl:
2702 return createCXString("ObjCInterfaceDecl");
2703 case CXCursor_ObjCCategoryDecl:
2704 return createCXString("ObjCCategoryDecl");
2705 case CXCursor_ObjCProtocolDecl:
2706 return createCXString("ObjCProtocolDecl");
2707 case CXCursor_ObjCPropertyDecl:
2708 return createCXString("ObjCPropertyDecl");
2709 case CXCursor_ObjCIvarDecl:
2710 return createCXString("ObjCIvarDecl");
2711 case CXCursor_ObjCInstanceMethodDecl:
2712 return createCXString("ObjCInstanceMethodDecl");
2713 case CXCursor_ObjCClassMethodDecl:
2714 return createCXString("ObjCClassMethodDecl");
2715 case CXCursor_ObjCImplementationDecl:
2716 return createCXString("ObjCImplementationDecl");
2717 case CXCursor_ObjCCategoryImplDecl:
2718 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002719 case CXCursor_CXXMethod:
2720 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002721 case CXCursor_UnexposedDecl:
2722 return createCXString("UnexposedDecl");
2723 case CXCursor_ObjCSuperClassRef:
2724 return createCXString("ObjCSuperClassRef");
2725 case CXCursor_ObjCProtocolRef:
2726 return createCXString("ObjCProtocolRef");
2727 case CXCursor_ObjCClassRef:
2728 return createCXString("ObjCClassRef");
2729 case CXCursor_TypeRef:
2730 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002731 case CXCursor_TemplateRef:
2732 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002733 case CXCursor_NamespaceRef:
2734 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002735 case CXCursor_MemberRef:
2736 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002737 case CXCursor_LabelRef:
2738 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002739 case CXCursor_OverloadedDeclRef:
2740 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002741 case CXCursor_UnexposedExpr:
2742 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002743 case CXCursor_BlockExpr:
2744 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002745 case CXCursor_DeclRefExpr:
2746 return createCXString("DeclRefExpr");
2747 case CXCursor_MemberRefExpr:
2748 return createCXString("MemberRefExpr");
2749 case CXCursor_CallExpr:
2750 return createCXString("CallExpr");
2751 case CXCursor_ObjCMessageExpr:
2752 return createCXString("ObjCMessageExpr");
2753 case CXCursor_UnexposedStmt:
2754 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002755 case CXCursor_LabelStmt:
2756 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002757 case CXCursor_InvalidFile:
2758 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002759 case CXCursor_InvalidCode:
2760 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002761 case CXCursor_NoDeclFound:
2762 return createCXString("NoDeclFound");
2763 case CXCursor_NotImplemented:
2764 return createCXString("NotImplemented");
2765 case CXCursor_TranslationUnit:
2766 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002767 case CXCursor_UnexposedAttr:
2768 return createCXString("UnexposedAttr");
2769 case CXCursor_IBActionAttr:
2770 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002771 case CXCursor_IBOutletAttr:
2772 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002773 case CXCursor_IBOutletCollectionAttr:
2774 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002775 case CXCursor_PreprocessingDirective:
2776 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002777 case CXCursor_MacroDefinition:
2778 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002779 case CXCursor_MacroInstantiation:
2780 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002781 case CXCursor_InclusionDirective:
2782 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002783 case CXCursor_Namespace:
2784 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002785 case CXCursor_LinkageSpec:
2786 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002787 case CXCursor_CXXBaseSpecifier:
2788 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002789 case CXCursor_Constructor:
2790 return createCXString("CXXConstructor");
2791 case CXCursor_Destructor:
2792 return createCXString("CXXDestructor");
2793 case CXCursor_ConversionFunction:
2794 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002795 case CXCursor_TemplateTypeParameter:
2796 return createCXString("TemplateTypeParameter");
2797 case CXCursor_NonTypeTemplateParameter:
2798 return createCXString("NonTypeTemplateParameter");
2799 case CXCursor_TemplateTemplateParameter:
2800 return createCXString("TemplateTemplateParameter");
2801 case CXCursor_FunctionTemplate:
2802 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002803 case CXCursor_ClassTemplate:
2804 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002805 case CXCursor_ClassTemplatePartialSpecialization:
2806 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002807 case CXCursor_NamespaceAlias:
2808 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002809 case CXCursor_UsingDirective:
2810 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002811 case CXCursor_UsingDeclaration:
2812 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002813 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002814
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002815 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002816 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002817}
Steve Naroff89922f82009-08-31 00:59:03 +00002818
Ted Kremeneke68fff62010-02-17 00:41:32 +00002819enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2820 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002821 CXClientData client_data) {
2822 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2823 *BestCursor = cursor;
2824 return CXChildVisit_Recurse;
2825}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002826
Douglas Gregorb9790342010-01-22 21:44:22 +00002827CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2828 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002829 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002830
Douglas Gregorb9790342010-01-22 21:44:22 +00002831 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002832 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2833
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002834 // Translate the given source location to make it point at the beginning of
2835 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002836 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002837
2838 // Guard against an invalid SourceLocation, or we may assert in one
2839 // of the following calls.
2840 if (SLoc.isInvalid())
2841 return clang_getNullCursor();
2842
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002843 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2844 CXXUnit->getASTContext().getLangOptions());
2845
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002846 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2847 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002848 // FIXME: Would be great to have a "hint" cursor, then walk from that
2849 // hint cursor upward until we find a cursor whose source range encloses
2850 // the region of interest, rather than starting from the translation unit.
2851 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002852 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002853 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002854 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002855 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002856 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002857}
2858
Ted Kremenek73885552009-11-17 19:28:59 +00002859CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002860 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002861}
2862
2863unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002864 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002865}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002866
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002867unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002868 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2869}
2870
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002871unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002872 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2873}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002874
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002875unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002876 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2877}
2878
Douglas Gregor97b98722010-01-19 23:20:36 +00002879unsigned clang_isExpression(enum CXCursorKind K) {
2880 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2881}
2882
2883unsigned clang_isStatement(enum CXCursorKind K) {
2884 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2885}
2886
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002887unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2888 return K == CXCursor_TranslationUnit;
2889}
2890
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002891unsigned clang_isPreprocessing(enum CXCursorKind K) {
2892 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2893}
2894
Ted Kremenekad6eff62010-03-08 21:17:29 +00002895unsigned clang_isUnexposed(enum CXCursorKind K) {
2896 switch (K) {
2897 case CXCursor_UnexposedDecl:
2898 case CXCursor_UnexposedExpr:
2899 case CXCursor_UnexposedStmt:
2900 case CXCursor_UnexposedAttr:
2901 return true;
2902 default:
2903 return false;
2904 }
2905}
2906
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002907CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002908 return C.kind;
2909}
2910
Douglas Gregor98258af2010-01-18 22:46:11 +00002911CXSourceLocation clang_getCursorLocation(CXCursor C) {
2912 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002913 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002914 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002915 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2916 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002917 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002918 }
2919
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002920 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002921 std::pair<ObjCProtocolDecl *, SourceLocation> P
2922 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002923 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002924 }
2925
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002926 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002927 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2928 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002929 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002930 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002931
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002932 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002933 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002934 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002935 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002936
2937 case CXCursor_TemplateRef: {
2938 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2939 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2940 }
2941
Douglas Gregor69319002010-08-31 23:48:11 +00002942 case CXCursor_NamespaceRef: {
2943 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2944 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2945 }
2946
Douglas Gregora67e03f2010-09-09 21:42:20 +00002947 case CXCursor_MemberRef: {
2948 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
2949 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2950 }
2951
Ted Kremenek3064ef92010-08-27 21:34:58 +00002952 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00002953 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
2954 if (!BaseSpec)
2955 return clang_getNullLocation();
2956
2957 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
2958 return cxloc::translateSourceLocation(getCursorContext(C),
2959 TSInfo->getTypeLoc().getBeginLoc());
2960
2961 return cxloc::translateSourceLocation(getCursorContext(C),
2962 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00002963 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002964
Douglas Gregor36897b02010-09-10 00:22:18 +00002965 case CXCursor_LabelRef: {
2966 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
2967 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
2968 }
2969
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002970 case CXCursor_OverloadedDeclRef:
2971 return cxloc::translateSourceLocation(getCursorContext(C),
2972 getCursorOverloadedDeclRef(C).second);
2973
Douglas Gregorf46034a2010-01-18 23:41:10 +00002974 default:
2975 // FIXME: Need a way to enumerate all non-reference cases.
2976 llvm_unreachable("Missed a reference kind");
2977 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002978 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002979
2980 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002981 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002982 getLocationFromExpr(getCursorExpr(C)));
2983
Douglas Gregor36897b02010-09-10 00:22:18 +00002984 if (clang_isStatement(C.kind))
2985 return cxloc::translateSourceLocation(getCursorContext(C),
2986 getCursorStmt(C)->getLocStart());
2987
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002988 if (C.kind == CXCursor_PreprocessingDirective) {
2989 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2990 return cxloc::translateSourceLocation(getCursorContext(C), L);
2991 }
Douglas Gregor48072312010-03-18 15:23:44 +00002992
2993 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002994 SourceLocation L
2995 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002996 return cxloc::translateSourceLocation(getCursorContext(C), L);
2997 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002998
2999 if (C.kind == CXCursor_MacroDefinition) {
3000 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3001 return cxloc::translateSourceLocation(getCursorContext(C), L);
3002 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003003
3004 if (C.kind == CXCursor_InclusionDirective) {
3005 SourceLocation L
3006 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3007 return cxloc::translateSourceLocation(getCursorContext(C), L);
3008 }
3009
Ted Kremenek9a700d22010-05-12 06:16:13 +00003010 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003011 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003012
Douglas Gregorf46034a2010-01-18 23:41:10 +00003013 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003014 SourceLocation Loc = D->getLocation();
3015 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3016 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003017 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003018}
Douglas Gregora7bde202010-01-19 00:34:46 +00003019
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003020} // end extern "C"
3021
3022static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003023 if (clang_isReference(C.kind)) {
3024 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003025 case CXCursor_ObjCSuperClassRef:
3026 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003027
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003028 case CXCursor_ObjCProtocolRef:
3029 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003030
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003031 case CXCursor_ObjCClassRef:
3032 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003033
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003034 case CXCursor_TypeRef:
3035 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003036
3037 case CXCursor_TemplateRef:
3038 return getCursorTemplateRef(C).second;
3039
Douglas Gregor69319002010-08-31 23:48:11 +00003040 case CXCursor_NamespaceRef:
3041 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003042
3043 case CXCursor_MemberRef:
3044 return getCursorMemberRef(C).second;
3045
Ted Kremenek3064ef92010-08-27 21:34:58 +00003046 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003047 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003048
Douglas Gregor36897b02010-09-10 00:22:18 +00003049 case CXCursor_LabelRef:
3050 return getCursorLabelRef(C).second;
3051
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003052 case CXCursor_OverloadedDeclRef:
3053 return getCursorOverloadedDeclRef(C).second;
3054
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003055 default:
3056 // FIXME: Need a way to enumerate all non-reference cases.
3057 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003058 }
3059 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003060
3061 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003062 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003063
3064 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003065 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003066
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003067 if (C.kind == CXCursor_PreprocessingDirective)
3068 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003069
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003070 if (C.kind == CXCursor_MacroInstantiation)
3071 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003072
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003073 if (C.kind == CXCursor_MacroDefinition)
3074 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003075
3076 if (C.kind == CXCursor_InclusionDirective)
3077 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3078
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003079 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
3080 return getCursorDecl(C)->getSourceRange();
3081
Douglas Gregorecdcb882010-10-20 22:00:55 +00003082 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003083
3084extern "C" {
3085
3086CXSourceRange clang_getCursorExtent(CXCursor C) {
3087 SourceRange R = getRawCursorExtent(C);
3088 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003089 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003090
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003091 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003092}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003093
3094CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003095 if (clang_isInvalid(C.kind))
3096 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003097
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003098 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003099 if (clang_isDeclaration(C.kind)) {
3100 Decl *D = getCursorDecl(C);
3101 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3102 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3103 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3104 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3105 if (ObjCForwardProtocolDecl *Protocols
3106 = dyn_cast<ObjCForwardProtocolDecl>(D))
3107 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3108
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003109 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003110 }
3111
Douglas Gregor97b98722010-01-19 23:20:36 +00003112 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003113 Expr *E = getCursorExpr(C);
3114 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003115 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003116 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003117
3118 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3119 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3120
Douglas Gregor97b98722010-01-19 23:20:36 +00003121 return clang_getNullCursor();
3122 }
3123
Douglas Gregor36897b02010-09-10 00:22:18 +00003124 if (clang_isStatement(C.kind)) {
3125 Stmt *S = getCursorStmt(C);
3126 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3127 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3128 getCursorASTUnit(C));
3129
3130 return clang_getNullCursor();
3131 }
3132
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003133 if (C.kind == CXCursor_MacroInstantiation) {
3134 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3135 return MakeMacroDefinitionCursor(Def, CXXUnit);
3136 }
3137
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003138 if (!clang_isReference(C.kind))
3139 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003140
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003141 switch (C.kind) {
3142 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003143 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003144
3145 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003146 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003147
3148 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003149 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003150
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003151 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003152 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003153
3154 case CXCursor_TemplateRef:
3155 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3156
Douglas Gregor69319002010-08-31 23:48:11 +00003157 case CXCursor_NamespaceRef:
3158 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3159
Douglas Gregora67e03f2010-09-09 21:42:20 +00003160 case CXCursor_MemberRef:
3161 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3162
Ted Kremenek3064ef92010-08-27 21:34:58 +00003163 case CXCursor_CXXBaseSpecifier: {
3164 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3165 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3166 CXXUnit));
3167 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003168
Douglas Gregor36897b02010-09-10 00:22:18 +00003169 case CXCursor_LabelRef:
3170 // FIXME: We end up faking the "parent" declaration here because we
3171 // don't want to make CXCursor larger.
3172 return MakeCXCursor(getCursorLabelRef(C).first,
3173 CXXUnit->getASTContext().getTranslationUnitDecl(),
3174 CXXUnit);
3175
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003176 case CXCursor_OverloadedDeclRef:
3177 return C;
3178
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003179 default:
3180 // We would prefer to enumerate all non-reference cursor kinds here.
3181 llvm_unreachable("Unhandled reference cursor kind");
3182 break;
3183 }
3184 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003185
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003186 return clang_getNullCursor();
3187}
3188
Douglas Gregorb6998662010-01-19 19:34:47 +00003189CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003190 if (clang_isInvalid(C.kind))
3191 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003192
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003193 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003194
Douglas Gregorb6998662010-01-19 19:34:47 +00003195 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003196 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003197 C = clang_getCursorReferenced(C);
3198 WasReference = true;
3199 }
3200
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003201 if (C.kind == CXCursor_MacroInstantiation)
3202 return clang_getCursorReferenced(C);
3203
Douglas Gregorb6998662010-01-19 19:34:47 +00003204 if (!clang_isDeclaration(C.kind))
3205 return clang_getNullCursor();
3206
3207 Decl *D = getCursorDecl(C);
3208 if (!D)
3209 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003210
Douglas Gregorb6998662010-01-19 19:34:47 +00003211 switch (D->getKind()) {
3212 // Declaration kinds that don't really separate the notions of
3213 // declaration and definition.
3214 case Decl::Namespace:
3215 case Decl::Typedef:
3216 case Decl::TemplateTypeParm:
3217 case Decl::EnumConstant:
3218 case Decl::Field:
3219 case Decl::ObjCIvar:
3220 case Decl::ObjCAtDefsField:
3221 case Decl::ImplicitParam:
3222 case Decl::ParmVar:
3223 case Decl::NonTypeTemplateParm:
3224 case Decl::TemplateTemplateParm:
3225 case Decl::ObjCCategoryImpl:
3226 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003227 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003228 case Decl::LinkageSpec:
3229 case Decl::ObjCPropertyImpl:
3230 case Decl::FileScopeAsm:
3231 case Decl::StaticAssert:
3232 case Decl::Block:
3233 return C;
3234
3235 // Declaration kinds that don't make any sense here, but are
3236 // nonetheless harmless.
3237 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003238 break;
3239
3240 // Declaration kinds for which the definition is not resolvable.
3241 case Decl::UnresolvedUsingTypename:
3242 case Decl::UnresolvedUsingValue:
3243 break;
3244
3245 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003246 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3247 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003248
3249 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003250 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003251
3252 case Decl::Enum:
3253 case Decl::Record:
3254 case Decl::CXXRecord:
3255 case Decl::ClassTemplateSpecialization:
3256 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003257 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003258 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003259 return clang_getNullCursor();
3260
3261 case Decl::Function:
3262 case Decl::CXXMethod:
3263 case Decl::CXXConstructor:
3264 case Decl::CXXDestructor:
3265 case Decl::CXXConversion: {
3266 const FunctionDecl *Def = 0;
3267 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003268 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003269 return clang_getNullCursor();
3270 }
3271
3272 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003273 // Ask the variable if it has a definition.
3274 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3275 return MakeCXCursor(Def, CXXUnit);
3276 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003277 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003278
Douglas Gregorb6998662010-01-19 19:34:47 +00003279 case Decl::FunctionTemplate: {
3280 const FunctionDecl *Def = 0;
3281 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003282 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003283 return clang_getNullCursor();
3284 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003285
Douglas Gregorb6998662010-01-19 19:34:47 +00003286 case Decl::ClassTemplate: {
3287 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003288 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003289 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003290 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003291 return clang_getNullCursor();
3292 }
3293
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003294 case Decl::Using:
3295 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3296 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003297
3298 case Decl::UsingShadow:
3299 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003300 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003301 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003302
3303 case Decl::ObjCMethod: {
3304 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3305 if (Method->isThisDeclarationADefinition())
3306 return C;
3307
3308 // Dig out the method definition in the associated
3309 // @implementation, if we have it.
3310 // FIXME: The ASTs should make finding the definition easier.
3311 if (ObjCInterfaceDecl *Class
3312 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3313 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3314 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3315 Method->isInstanceMethod()))
3316 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003317 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003318
3319 return clang_getNullCursor();
3320 }
3321
3322 case Decl::ObjCCategory:
3323 if (ObjCCategoryImplDecl *Impl
3324 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003325 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003326 return clang_getNullCursor();
3327
3328 case Decl::ObjCProtocol:
3329 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3330 return C;
3331 return clang_getNullCursor();
3332
3333 case Decl::ObjCInterface:
3334 // There are two notions of a "definition" for an Objective-C
3335 // class: the interface and its implementation. When we resolved a
3336 // reference to an Objective-C class, produce the @interface as
3337 // the definition; when we were provided with the interface,
3338 // produce the @implementation as the definition.
3339 if (WasReference) {
3340 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3341 return C;
3342 } else if (ObjCImplementationDecl *Impl
3343 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003344 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003345 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003346
Douglas Gregorb6998662010-01-19 19:34:47 +00003347 case Decl::ObjCProperty:
3348 // FIXME: We don't really know where to find the
3349 // ObjCPropertyImplDecls that implement this property.
3350 return clang_getNullCursor();
3351
3352 case Decl::ObjCCompatibleAlias:
3353 if (ObjCInterfaceDecl *Class
3354 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3355 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003356 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003357
Douglas Gregorb6998662010-01-19 19:34:47 +00003358 return clang_getNullCursor();
3359
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003360 case Decl::ObjCForwardProtocol:
3361 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3362 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003363
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003364 case Decl::ObjCClass:
3365 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3366 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003367
3368 case Decl::Friend:
3369 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003370 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003371 return clang_getNullCursor();
3372
3373 case Decl::FriendTemplate:
3374 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003375 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003376 return clang_getNullCursor();
3377 }
3378
3379 return clang_getNullCursor();
3380}
3381
3382unsigned clang_isCursorDefinition(CXCursor C) {
3383 if (!clang_isDeclaration(C.kind))
3384 return 0;
3385
3386 return clang_getCursorDefinition(C) == C;
3387}
3388
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003389unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003390 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003391 return 0;
3392
3393 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3394 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3395 return E->getNumDecls();
3396
3397 if (OverloadedTemplateStorage *S
3398 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3399 return S->size();
3400
3401 Decl *D = Storage.get<Decl*>();
3402 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3403 return Using->getNumShadowDecls();
3404 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3405 return Classes->size();
3406 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3407 return Protocols->protocol_size();
3408
3409 return 0;
3410}
3411
3412CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003413 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003414 return clang_getNullCursor();
3415
3416 if (index >= clang_getNumOverloadedDecls(cursor))
3417 return clang_getNullCursor();
3418
3419 ASTUnit *Unit = getCursorASTUnit(cursor);
3420 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3421 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3422 return MakeCXCursor(E->decls_begin()[index], Unit);
3423
3424 if (OverloadedTemplateStorage *S
3425 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3426 return MakeCXCursor(S->begin()[index], Unit);
3427
3428 Decl *D = Storage.get<Decl*>();
3429 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3430 // FIXME: This is, unfortunately, linear time.
3431 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3432 std::advance(Pos, index);
3433 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3434 }
3435
3436 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3437 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3438
3439 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3440 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3441
3442 return clang_getNullCursor();
3443}
3444
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003445void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003446 const char **startBuf,
3447 const char **endBuf,
3448 unsigned *startLine,
3449 unsigned *startColumn,
3450 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003451 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003452 assert(getCursorDecl(C) && "CXCursor has null decl");
3453 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003454 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3455 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003456
Steve Naroff4ade6d62009-09-23 17:52:52 +00003457 SourceManager &SM = FD->getASTContext().getSourceManager();
3458 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3459 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3460 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3461 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3462 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3463 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3464}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003465
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003466void clang_enableStackTraces(void) {
3467 llvm::sys::PrintStackTraceOnErrorSignal();
3468}
3469
Ted Kremenekfb480492010-01-13 21:46:36 +00003470} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003471
Ted Kremenekfb480492010-01-13 21:46:36 +00003472//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003473// Token-based Operations.
3474//===----------------------------------------------------------------------===//
3475
3476/* CXToken layout:
3477 * int_data[0]: a CXTokenKind
3478 * int_data[1]: starting token location
3479 * int_data[2]: token length
3480 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003481 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003482 * otherwise unused.
3483 */
3484extern "C" {
3485
3486CXTokenKind clang_getTokenKind(CXToken CXTok) {
3487 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3488}
3489
3490CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3491 switch (clang_getTokenKind(CXTok)) {
3492 case CXToken_Identifier:
3493 case CXToken_Keyword:
3494 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003495 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3496 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003497
3498 case CXToken_Literal: {
3499 // We have stashed the starting pointer in the ptr_data field. Use it.
3500 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003501 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003502 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003503
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003504 case CXToken_Punctuation:
3505 case CXToken_Comment:
3506 break;
3507 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003508
3509 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003510 // deconstructing the source location.
3511 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3512 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003513 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003514
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003515 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3516 std::pair<FileID, unsigned> LocInfo
3517 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003518 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003519 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003520 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3521 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003522 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003523
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003524 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003525}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003526
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003527CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3528 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3529 if (!CXXUnit)
3530 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003531
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003532 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3533 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3534}
3535
3536CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3537 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003538 if (!CXXUnit)
3539 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003540
3541 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003542 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3543}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003544
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003545void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3546 CXToken **Tokens, unsigned *NumTokens) {
3547 if (Tokens)
3548 *Tokens = 0;
3549 if (NumTokens)
3550 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003551
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003552 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3553 if (!CXXUnit || !Tokens || !NumTokens)
3554 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003555
Douglas Gregorbdf60622010-03-05 21:16:25 +00003556 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3557
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003558 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003559 if (R.isInvalid())
3560 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003561
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003562 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3563 std::pair<FileID, unsigned> BeginLocInfo
3564 = SourceMgr.getDecomposedLoc(R.getBegin());
3565 std::pair<FileID, unsigned> EndLocInfo
3566 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003567
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003568 // Cannot tokenize across files.
3569 if (BeginLocInfo.first != EndLocInfo.first)
3570 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003571
3572 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003573 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003574 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003575 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003576 if (Invalid)
3577 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003578
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003579 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3580 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003581 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003582 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003583
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003584 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003585 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003586 llvm::SmallVector<CXToken, 32> CXTokens;
3587 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003588 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003589 do {
3590 // Lex the next token
3591 Lex.LexFromRawLexer(Tok);
3592 if (Tok.is(tok::eof))
3593 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003594
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003595 // Initialize the CXToken.
3596 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003597
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003598 // - Common fields
3599 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3600 CXTok.int_data[2] = Tok.getLength();
3601 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003602
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003603 // - Kind-specific fields
3604 if (Tok.isLiteral()) {
3605 CXTok.int_data[0] = CXToken_Literal;
3606 CXTok.ptr_data = (void *)Tok.getLiteralData();
3607 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003608 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003609 std::pair<FileID, unsigned> LocInfo
3610 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003611 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003612 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003613 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3614 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003615 return;
3616
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003617 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003618 IdentifierInfo *II
3619 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003620
David Chisnall096428b2010-10-13 21:44:48 +00003621 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003622 CXTok.int_data[0] = CXToken_Keyword;
3623 }
3624 else {
3625 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3626 CXToken_Identifier
3627 : CXToken_Keyword;
3628 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003629 CXTok.ptr_data = II;
3630 } else if (Tok.is(tok::comment)) {
3631 CXTok.int_data[0] = CXToken_Comment;
3632 CXTok.ptr_data = 0;
3633 } else {
3634 CXTok.int_data[0] = CXToken_Punctuation;
3635 CXTok.ptr_data = 0;
3636 }
3637 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003638 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003639 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003640
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003641 if (CXTokens.empty())
3642 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003643
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003644 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3645 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3646 *NumTokens = CXTokens.size();
3647}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003648
Ted Kremenek6db61092010-05-05 00:55:15 +00003649void clang_disposeTokens(CXTranslationUnit TU,
3650 CXToken *Tokens, unsigned NumTokens) {
3651 free(Tokens);
3652}
3653
3654} // end: extern "C"
3655
3656//===----------------------------------------------------------------------===//
3657// Token annotation APIs.
3658//===----------------------------------------------------------------------===//
3659
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003660typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003661static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3662 CXCursor parent,
3663 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003664namespace {
3665class AnnotateTokensWorker {
3666 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003667 CXToken *Tokens;
3668 CXCursor *Cursors;
3669 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003670 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003671 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003672 CursorVisitor AnnotateVis;
3673 SourceManager &SrcMgr;
3674
3675 bool MoreTokens() const { return TokIdx < NumTokens; }
3676 unsigned NextToken() const { return TokIdx; }
3677 void AdvanceToken() { ++TokIdx; }
3678 SourceLocation GetTokenLoc(unsigned tokI) {
3679 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3680 }
3681
Ted Kremenek6db61092010-05-05 00:55:15 +00003682public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003683 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003684 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3685 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003686 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003687 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003688 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3689 Decl::MaxPCHLevel, RegionOfInterest),
3690 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003691
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003692 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003693 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003694 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003695};
3696}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003697
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003698void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3699 // Walk the AST within the region of interest, annotating tokens
3700 // along the way.
3701 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003702
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003703 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3704 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003705 if (Pos != Annotated.end() &&
3706 (clang_isInvalid(Cursors[I].kind) ||
3707 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003708 Cursors[I] = Pos->second;
3709 }
3710
3711 // Finish up annotating any tokens left.
3712 if (!MoreTokens())
3713 return;
3714
3715 const CXCursor &C = clang_getNullCursor();
3716 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3717 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3718 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003719 }
3720}
3721
Ted Kremenek6db61092010-05-05 00:55:15 +00003722enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00003723AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003724 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00003725 SourceRange cursorRange = getRawCursorExtent(cursor);
3726
3727 if (clang_isPreprocessing(cursor.kind)) {
3728 // For macro instantiations, just note where the beginning of the macro
3729 // instantiation occurs.
3730 if (cursor.kind == CXCursor_MacroInstantiation) {
3731 Annotated[Loc.int_data] = cursor;
3732 return CXChildVisit_Recurse;
3733 }
3734
3735 if (cursorRange.isInvalid())
3736 return CXChildVisit_Continue;
3737
3738 // Items in the preprocessing record are kept separate from items in
3739 // declarations, so we keep a separate token index.
3740 unsigned SavedTokIdx = TokIdx;
3741 TokIdx = PreprocessingTokIdx;
3742
3743 // Skip tokens up until we catch up to the beginning of the preprocessing
3744 // entry.
3745 while (MoreTokens()) {
3746 const unsigned I = NextToken();
3747 SourceLocation TokLoc = GetTokenLoc(I);
3748 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3749 case RangeBefore:
3750 AdvanceToken();
3751 continue;
3752 case RangeAfter:
3753 case RangeOverlap:
3754 break;
3755 }
3756 break;
3757 }
3758
3759 // Look at all of the tokens within this range.
3760 while (MoreTokens()) {
3761 const unsigned I = NextToken();
3762 SourceLocation TokLoc = GetTokenLoc(I);
3763 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3764 case RangeBefore:
3765 assert(0 && "Infeasible");
3766 case RangeAfter:
3767 break;
3768 case RangeOverlap:
3769 Cursors[I] = cursor;
3770 AdvanceToken();
3771 continue;
3772 }
3773 break;
3774 }
3775
3776 // Save the preprocessing token index; restore the non-preprocessing
3777 // token index.
3778 PreprocessingTokIdx = TokIdx;
3779 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003780 return CXChildVisit_Recurse;
3781 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003782
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003783 if (cursorRange.isInvalid())
3784 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003785
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003786 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3787
Ted Kremeneka333c662010-05-12 05:29:33 +00003788 // Adjust the annotated range based specific declarations.
3789 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3790 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003791 Decl *D = cxcursor::getCursorDecl(cursor);
3792 // Don't visit synthesized ObjC methods, since they have no syntatic
3793 // representation in the source.
3794 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3795 if (MD->isSynthesized())
3796 return CXChildVisit_Continue;
3797 }
3798 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003799 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3800 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003801 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003802 if (TLoc.isValid() &&
3803 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003804 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003805 }
3806 }
3807 }
3808
Ted Kremenek3f404602010-08-14 01:14:06 +00003809 // If the location of the cursor occurs within a macro instantiation, record
3810 // the spelling location of the cursor in our annotation map. We can then
3811 // paper over the token labelings during a post-processing step to try and
3812 // get cursor mappings for tokens that are the *arguments* of a macro
3813 // instantiation.
3814 if (L.isMacroID()) {
3815 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3816 // Only invalidate the old annotation if it isn't part of a preprocessing
3817 // directive. Here we assume that the default construction of CXCursor
3818 // results in CXCursor.kind being an initialized value (i.e., 0). If
3819 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00003820
Ted Kremenek3f404602010-08-14 01:14:06 +00003821 CXCursor &oldC = Annotated[rawEncoding];
3822 if (!clang_isPreprocessing(oldC.kind))
3823 oldC = cursor;
3824 }
3825
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003826 const enum CXCursorKind K = clang_getCursorKind(parent);
3827 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003828 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3829 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003830
3831 while (MoreTokens()) {
3832 const unsigned I = NextToken();
3833 SourceLocation TokLoc = GetTokenLoc(I);
3834 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3835 case RangeBefore:
3836 Cursors[I] = updateC;
3837 AdvanceToken();
3838 continue;
3839 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003840 case RangeOverlap:
3841 break;
3842 }
3843 break;
3844 }
3845
3846 // Visit children to get their cursor information.
3847 const unsigned BeforeChildren = NextToken();
3848 VisitChildren(cursor);
3849 const unsigned AfterChildren = NextToken();
3850
3851 // Adjust 'Last' to the last token within the extent of the cursor.
3852 while (MoreTokens()) {
3853 const unsigned I = NextToken();
3854 SourceLocation TokLoc = GetTokenLoc(I);
3855 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3856 case RangeBefore:
3857 assert(0 && "Infeasible");
3858 case RangeAfter:
3859 break;
3860 case RangeOverlap:
3861 Cursors[I] = updateC;
3862 AdvanceToken();
3863 continue;
3864 }
3865 break;
3866 }
3867 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003868
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003869 // Scan the tokens that are at the beginning of the cursor, but are not
3870 // capture by the child cursors.
3871
3872 // For AST elements within macros, rely on a post-annotate pass to
3873 // to correctly annotate the tokens with cursors. Otherwise we can
3874 // get confusing results of having tokens that map to cursors that really
3875 // are expanded by an instantiation.
3876 if (L.isMacroID())
3877 cursor = clang_getNullCursor();
3878
3879 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3880 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3881 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00003882
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003883 Cursors[I] = cursor;
3884 }
3885 // Scan the tokens that are at the end of the cursor, but are not captured
3886 // but the child cursors.
3887 for (unsigned I = AfterChildren; I != Last; ++I)
3888 Cursors[I] = cursor;
3889
3890 TokIdx = Last;
3891 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003892}
3893
Ted Kremenek6db61092010-05-05 00:55:15 +00003894static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3895 CXCursor parent,
3896 CXClientData client_data) {
3897 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3898}
3899
3900extern "C" {
3901
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003902void clang_annotateTokens(CXTranslationUnit TU,
3903 CXToken *Tokens, unsigned NumTokens,
3904 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003905
3906 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003907 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003908
Douglas Gregor4419b672010-10-21 06:10:04 +00003909 // Any token we don't specifically annotate will have a NULL cursor.
3910 CXCursor C = clang_getNullCursor();
3911 for (unsigned I = 0; I != NumTokens; ++I)
3912 Cursors[I] = C;
3913
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003914 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00003915 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003916 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003917
Douglas Gregorbdf60622010-03-05 21:16:25 +00003918 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003919
Douglas Gregor0396f462010-03-19 05:22:59 +00003920 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003921 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003922 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3923 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003924 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3925 clang_getTokenLocation(TU,
3926 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003927
Douglas Gregor0396f462010-03-19 05:22:59 +00003928 // A mapping from the source locations found when re-lexing or traversing the
3929 // region of interest to the corresponding cursors.
3930 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003931
3932 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003933 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003934 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3935 std::pair<FileID, unsigned> BeginLocInfo
3936 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3937 std::pair<FileID, unsigned> EndLocInfo
3938 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003939
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003940 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003941 bool Invalid = false;
3942 if (BeginLocInfo.first == EndLocInfo.first &&
3943 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3944 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003945 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3946 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003947 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003948 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003949 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003950
3951 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003952 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003953 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003954 Token Tok;
3955 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003956
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003957 reprocess:
3958 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3959 // We have found a preprocessing directive. Gobble it up so that we
3960 // don't see it while preprocessing these tokens later, but keep track of
3961 // all of the token locations inside this preprocessing directive so that
3962 // we can annotate them appropriately.
3963 //
3964 // FIXME: Some simple tests here could identify macro definitions and
3965 // #undefs, to provide specific cursor kinds for those.
3966 std::vector<SourceLocation> Locations;
3967 do {
3968 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003969 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003970 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003971
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003972 using namespace cxcursor;
3973 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003974 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3975 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003976 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003977 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3978 Annotated[Locations[I].getRawEncoding()] = Cursor;
3979 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003980
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003981 if (Tok.isAtStartOfLine())
3982 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003983
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003984 continue;
3985 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003986
Douglas Gregor48072312010-03-18 15:23:44 +00003987 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003988 break;
3989 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003990 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003991
Douglas Gregor0396f462010-03-19 05:22:59 +00003992 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003993 // a specific cursor.
3994 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3995 CXXUnit, RegionOfInterest);
3996 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003997}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003998} // end: extern "C"
3999
4000//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004001// Operations for querying linkage of a cursor.
4002//===----------------------------------------------------------------------===//
4003
4004extern "C" {
4005CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004006 if (!clang_isDeclaration(cursor.kind))
4007 return CXLinkage_Invalid;
4008
Ted Kremenek16b42592010-03-03 06:36:57 +00004009 Decl *D = cxcursor::getCursorDecl(cursor);
4010 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4011 switch (ND->getLinkage()) {
4012 case NoLinkage: return CXLinkage_NoLinkage;
4013 case InternalLinkage: return CXLinkage_Internal;
4014 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4015 case ExternalLinkage: return CXLinkage_External;
4016 };
4017
4018 return CXLinkage_Invalid;
4019}
4020} // end: extern "C"
4021
4022//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004023// Operations for querying language of a cursor.
4024//===----------------------------------------------------------------------===//
4025
4026static CXLanguageKind getDeclLanguage(const Decl *D) {
4027 switch (D->getKind()) {
4028 default:
4029 break;
4030 case Decl::ImplicitParam:
4031 case Decl::ObjCAtDefsField:
4032 case Decl::ObjCCategory:
4033 case Decl::ObjCCategoryImpl:
4034 case Decl::ObjCClass:
4035 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004036 case Decl::ObjCForwardProtocol:
4037 case Decl::ObjCImplementation:
4038 case Decl::ObjCInterface:
4039 case Decl::ObjCIvar:
4040 case Decl::ObjCMethod:
4041 case Decl::ObjCProperty:
4042 case Decl::ObjCPropertyImpl:
4043 case Decl::ObjCProtocol:
4044 return CXLanguage_ObjC;
4045 case Decl::CXXConstructor:
4046 case Decl::CXXConversion:
4047 case Decl::CXXDestructor:
4048 case Decl::CXXMethod:
4049 case Decl::CXXRecord:
4050 case Decl::ClassTemplate:
4051 case Decl::ClassTemplatePartialSpecialization:
4052 case Decl::ClassTemplateSpecialization:
4053 case Decl::Friend:
4054 case Decl::FriendTemplate:
4055 case Decl::FunctionTemplate:
4056 case Decl::LinkageSpec:
4057 case Decl::Namespace:
4058 case Decl::NamespaceAlias:
4059 case Decl::NonTypeTemplateParm:
4060 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004061 case Decl::TemplateTemplateParm:
4062 case Decl::TemplateTypeParm:
4063 case Decl::UnresolvedUsingTypename:
4064 case Decl::UnresolvedUsingValue:
4065 case Decl::Using:
4066 case Decl::UsingDirective:
4067 case Decl::UsingShadow:
4068 return CXLanguage_CPlusPlus;
4069 }
4070
4071 return CXLanguage_C;
4072}
4073
4074extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004075
4076enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4077 if (clang_isDeclaration(cursor.kind))
4078 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4079 if (D->hasAttr<UnavailableAttr>() ||
4080 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4081 return CXAvailability_Available;
4082
4083 if (D->hasAttr<DeprecatedAttr>())
4084 return CXAvailability_Deprecated;
4085 }
4086
4087 return CXAvailability_Available;
4088}
4089
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004090CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4091 if (clang_isDeclaration(cursor.kind))
4092 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4093
4094 return CXLanguage_Invalid;
4095}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004096
4097CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4098 if (clang_isDeclaration(cursor.kind)) {
4099 if (Decl *D = getCursorDecl(cursor)) {
4100 DeclContext *DC = D->getDeclContext();
4101 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4102 }
4103 }
4104
4105 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4106 if (Decl *D = getCursorDecl(cursor))
4107 return MakeCXCursor(D, getCursorASTUnit(cursor));
4108 }
4109
4110 return clang_getNullCursor();
4111}
4112
4113CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4114 if (clang_isDeclaration(cursor.kind)) {
4115 if (Decl *D = getCursorDecl(cursor)) {
4116 DeclContext *DC = D->getLexicalDeclContext();
4117 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4118 }
4119 }
4120
4121 // FIXME: Note that we can't easily compute the lexical context of a
4122 // statement or expression, so we return nothing.
4123 return clang_getNullCursor();
4124}
4125
Douglas Gregor9f592342010-10-01 20:25:15 +00004126static void CollectOverriddenMethods(DeclContext *Ctx,
4127 ObjCMethodDecl *Method,
4128 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4129 if (!Ctx)
4130 return;
4131
4132 // If we have a class or category implementation, jump straight to the
4133 // interface.
4134 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4135 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4136
4137 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4138 if (!Container)
4139 return;
4140
4141 // Check whether we have a matching method at this level.
4142 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4143 Method->isInstanceMethod()))
4144 if (Method != Overridden) {
4145 // We found an override at this level; there is no need to look
4146 // into other protocols or categories.
4147 Methods.push_back(Overridden);
4148 return;
4149 }
4150
4151 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4152 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4153 PEnd = Protocol->protocol_end();
4154 P != PEnd; ++P)
4155 CollectOverriddenMethods(*P, Method, Methods);
4156 }
4157
4158 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4159 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4160 PEnd = Category->protocol_end();
4161 P != PEnd; ++P)
4162 CollectOverriddenMethods(*P, Method, Methods);
4163 }
4164
4165 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4166 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4167 PEnd = Interface->protocol_end();
4168 P != PEnd; ++P)
4169 CollectOverriddenMethods(*P, Method, Methods);
4170
4171 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4172 Category; Category = Category->getNextClassCategory())
4173 CollectOverriddenMethods(Category, Method, Methods);
4174
4175 // We only look into the superclass if we haven't found anything yet.
4176 if (Methods.empty())
4177 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4178 return CollectOverriddenMethods(Super, Method, Methods);
4179 }
4180}
4181
4182void clang_getOverriddenCursors(CXCursor cursor,
4183 CXCursor **overridden,
4184 unsigned *num_overridden) {
4185 if (overridden)
4186 *overridden = 0;
4187 if (num_overridden)
4188 *num_overridden = 0;
4189 if (!overridden || !num_overridden)
4190 return;
4191
4192 if (!clang_isDeclaration(cursor.kind))
4193 return;
4194
4195 Decl *D = getCursorDecl(cursor);
4196 if (!D)
4197 return;
4198
4199 // Handle C++ member functions.
4200 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4201 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4202 *num_overridden = CXXMethod->size_overridden_methods();
4203 if (!*num_overridden)
4204 return;
4205
4206 *overridden = new CXCursor [*num_overridden];
4207 unsigned I = 0;
4208 for (CXXMethodDecl::method_iterator
4209 M = CXXMethod->begin_overridden_methods(),
4210 MEnd = CXXMethod->end_overridden_methods();
4211 M != MEnd; (void)++M, ++I)
4212 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4213 return;
4214 }
4215
4216 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4217 if (!Method)
4218 return;
4219
4220 // Handle Objective-C methods.
4221 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4222 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4223
4224 if (Methods.empty())
4225 return;
4226
4227 *num_overridden = Methods.size();
4228 *overridden = new CXCursor [Methods.size()];
4229 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4230 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4231}
4232
4233void clang_disposeOverriddenCursors(CXCursor *overridden) {
4234 delete [] overridden;
4235}
4236
Douglas Gregorecdcb882010-10-20 22:00:55 +00004237CXFile clang_getIncludedFile(CXCursor cursor) {
4238 if (cursor.kind != CXCursor_InclusionDirective)
4239 return 0;
4240
4241 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4242 return (void *)ID->getFile();
4243}
4244
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004245} // end: extern "C"
4246
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004247
4248//===----------------------------------------------------------------------===//
4249// C++ AST instrospection.
4250//===----------------------------------------------------------------------===//
4251
4252extern "C" {
4253unsigned clang_CXXMethod_isStatic(CXCursor C) {
4254 if (!clang_isDeclaration(C.kind))
4255 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004256
4257 CXXMethodDecl *Method = 0;
4258 Decl *D = cxcursor::getCursorDecl(C);
4259 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4260 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4261 else
4262 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4263 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004264}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004265
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004266} // end: extern "C"
4267
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004268//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004269// Attribute introspection.
4270//===----------------------------------------------------------------------===//
4271
4272extern "C" {
4273CXType clang_getIBOutletCollectionType(CXCursor C) {
4274 if (C.kind != CXCursor_IBOutletCollectionAttr)
4275 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4276
4277 IBOutletCollectionAttr *A =
4278 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4279
4280 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4281}
4282} // end: extern "C"
4283
4284//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004285// CXString Operations.
4286//===----------------------------------------------------------------------===//
4287
4288extern "C" {
4289const char *clang_getCString(CXString string) {
4290 return string.Spelling;
4291}
4292
4293void clang_disposeString(CXString string) {
4294 if (string.MustFreeString && string.Spelling)
4295 free((void*)string.Spelling);
4296}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004297
Ted Kremenekfb480492010-01-13 21:46:36 +00004298} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004299
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004300namespace clang { namespace cxstring {
4301CXString createCXString(const char *String, bool DupString){
4302 CXString Str;
4303 if (DupString) {
4304 Str.Spelling = strdup(String);
4305 Str.MustFreeString = 1;
4306 } else {
4307 Str.Spelling = String;
4308 Str.MustFreeString = 0;
4309 }
4310 return Str;
4311}
4312
4313CXString createCXString(llvm::StringRef String, bool DupString) {
4314 CXString Result;
4315 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4316 char *Spelling = (char *)malloc(String.size() + 1);
4317 memmove(Spelling, String.data(), String.size());
4318 Spelling[String.size()] = 0;
4319 Result.Spelling = Spelling;
4320 Result.MustFreeString = 1;
4321 } else {
4322 Result.Spelling = String.data();
4323 Result.MustFreeString = 0;
4324 }
4325 return Result;
4326}
4327}}
4328
Ted Kremenek04bb7162010-01-22 22:44:15 +00004329//===----------------------------------------------------------------------===//
4330// Misc. utility functions.
4331//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004332
Ted Kremenek04bb7162010-01-22 22:44:15 +00004333extern "C" {
4334
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004335CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004336 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004337}
4338
4339} // end: extern "C"