blob: 35e28ad42989e608f3be049283ec1b99be397b08 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000033#include "llvm/ADT/STLExtras.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000034#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor02465752009-10-16 21:24:31 +000035#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000036#include "llvm/Support/Timer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000037#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000038#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000039
Benjamin Kramerc2a98162010-03-13 21:22:49 +000040// Needed to define L_TMPNAM on some systems.
41#include <cstdio>
42
Steve Naroff50398192009-08-28 15:28:48 +000043using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000044using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000045using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000046
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000047//===----------------------------------------------------------------------===//
48// Crash Reporting.
49//===----------------------------------------------------------------------===//
50
Ted Kremenekd7ffd082010-05-22 00:06:46 +000051#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000052#include "clang/Analysis/Support/SaveAndRestore.h"
53// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000054static const char *__crashreporter_info__ = 0;
55asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000056#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000057static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000058static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000059static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
60static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
61
62static unsigned SetCrashTracerInfo(const char *str,
63 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000064
Ted Kremenek254ba7c2010-01-07 23:13:53 +000065 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000066 while (crashtracer_strings[slot]) {
67 if (++slot == NUM_CRASH_STRINGS)
68 slot = 0;
69 }
70 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000071 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000072
73 // We need to create an aggregate string because multiple threads
74 // may be in this method at one time. The crash reporter string
75 // will attempt to overapproximate the set of in-flight invocations
76 // of this function. Race conditions can still cause this goal
77 // to not be achieved.
78 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000079 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000080 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
81 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
82 }
83 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
84 return slot;
85}
86
87static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000088 unsigned max_slot = 0;
89 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000090
Ted Kremenek254ba7c2010-01-07 23:13:53 +000091 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
92
93 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
94 if (agg_crashtracer_strings[i] &&
95 crashtracer_counter_id[i] > max_value) {
96 max_slot = i;
97 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000098 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000099
100 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +0000101}
102
103namespace {
104class ArgsCrashTracerInfo {
105 llvm::SmallString<1024> CrashString;
106 llvm::SmallString<1024> AggregateString;
107 unsigned crashtracerSlot;
108public:
109 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
110 : crashtracerSlot(0)
111 {
112 {
113 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000114 Out << "ClangCIndex [" << getClangFullVersion() << "]"
115 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000116 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
117 E=Args.end(); I!=E; ++I)
118 Out << ' ' << *I;
119 }
120 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
121 AggregateString);
122 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000123
Ted Kremenek29b72842010-01-07 22:49:05 +0000124 ~ArgsCrashTracerInfo() {
125 ResetCrashTracerInfo(crashtracerSlot);
126 }
127};
128}
129#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000130
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000131/// \brief The result of comparing two source ranges.
132enum RangeComparisonResult {
133 /// \brief Either the ranges overlap or one of the ranges is invalid.
134 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000135
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000136 /// \brief The first range ends before the second range starts.
137 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000138
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000139 /// \brief The first range starts after the second range ends.
140 RangeAfter
141};
142
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000143/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000144/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000145static RangeComparisonResult RangeCompare(SourceManager &SM,
146 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000147 SourceRange R2) {
148 assert(R1.isValid() && "First range is invalid?");
149 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000150 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000151 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000152 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000153 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000154 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000155 return RangeAfter;
156 return RangeOverlap;
157}
158
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000159/// \brief Determine if a source location falls within, before, or after a
160/// a given source range.
161static RangeComparisonResult LocationCompare(SourceManager &SM,
162 SourceLocation L, SourceRange R) {
163 assert(R.isValid() && "First range is invalid?");
164 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000165 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000166 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000167 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
168 return RangeBefore;
169 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
170 return RangeAfter;
171 return RangeOverlap;
172}
173
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000174/// \brief Translate a Clang source range into a CIndex source range.
175///
176/// Clang internally represents ranges where the end location points to the
177/// start of the token at the end. However, for external clients it is more
178/// useful to have a CXSourceRange be a proper half-open interval. This routine
179/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000180CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000181 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000182 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000183 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000184 // location accordingly.
185 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000186 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000187 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000188 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000189 EndLoc = EndLoc.getFileLocWithOffset(Length);
190 }
191
192 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
193 R.getBegin().getRawEncoding(),
194 EndLoc.getRawEncoding() };
195 return Result;
196}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000197
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000198//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000199// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000200//===----------------------------------------------------------------------===//
201
Steve Naroff89922f82009-08-31 00:59:03 +0000202namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000203
Douglas Gregorb1373d02010-01-20 20:59:29 +0000204// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000205class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000206 public TypeLocVisitor<CursorVisitor, bool>,
207 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000208{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000209 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000210 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000211
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000212 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000213 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000215 /// \brief The declaration that serves at the parent of any statement or
216 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000217 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000218
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000219 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000221
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000222 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000223 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000224
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000225 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
226 // to the visitor. Declarations with a PCH level greater than this value will
227 // be suppressed.
228 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000229
230 /// \brief When valid, a source range to which the cursor should restrict
231 /// its search.
232 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000233
Douglas Gregorb1373d02010-01-20 20:59:29 +0000234 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000235 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000236 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000237
238 /// \brief Determine whether this particular source range comes before, comes
239 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000240 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000241 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000242 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
243
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000244 class SetParentRAII {
245 CXCursor &Parent;
246 Decl *&StmtParent;
247 CXCursor OldParent;
248
249 public:
250 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
251 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
252 {
253 Parent = NewParent;
254 if (clang_isDeclaration(Parent.kind))
255 StmtParent = getCursorDecl(Parent);
256 }
257
258 ~SetParentRAII() {
259 Parent = OldParent;
260 if (clang_isDeclaration(Parent.kind))
261 StmtParent = getCursorDecl(Parent);
262 }
263 };
264
Steve Naroff89922f82009-08-31 00:59:03 +0000265public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000266 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
267 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000268 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000269 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000270 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000271 {
272 Parent.kind = CXCursor_NoDeclFound;
273 Parent.data[0] = 0;
274 Parent.data[1] = 0;
275 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000276 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000277 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000278
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000279 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000280
281 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
282 getPreprocessedEntities();
283
Douglas Gregorb1373d02010-01-20 20:59:29 +0000284 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000285
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000286 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000287 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000288 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000289 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000290 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000291 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
292 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000293 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000294 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000295 bool VisitClassTemplatePartialSpecializationDecl(
296 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000297 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000298 bool VisitEnumConstantDecl(EnumConstantDecl *D);
299 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
300 bool VisitFunctionDecl(FunctionDecl *ND);
301 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000302 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000303 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000304 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000305 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000306 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000307 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
308 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
309 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
310 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000311 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000312 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
313 bool VisitObjCImplDecl(ObjCImplDecl *D);
314 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
315 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000316 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
317 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
318 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000319 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000320 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000321 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000322 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000323 bool VisitUsingDecl(UsingDecl *D);
324 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
325 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000326
Douglas Gregor01829d32010-08-31 14:41:23 +0000327 // Name visitor
328 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000329 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000330
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000331 // Template visitors
332 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000333 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000334 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
335
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000336 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000337 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000338 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000339 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000340 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
341 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000342 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000343 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000344 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000345 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
346 bool VisitPointerTypeLoc(PointerTypeLoc TL);
347 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
348 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
349 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
350 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000351 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000352 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000353 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000354 // FIXME: Implement visitors here when the unimplemented TypeLocs get
355 // implemented
356 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
357 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000358
Douglas Gregora59e3902010-01-21 23:27:09 +0000359 // Statement visitors
360 bool VisitStmt(Stmt *S);
361 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000362 // FIXME: LabelStmt label?
363 bool VisitIfStmt(IfStmt *S);
364 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000365 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000366 bool VisitWhileStmt(WhileStmt *S);
367 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000368
Douglas Gregor336fd812010-01-23 00:40:08 +0000369 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000370 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000371 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000372 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000373 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000374 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000375 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000376 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000377 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000378 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfbb4c982010-09-02 21:07:44 +0000379 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000380 // FIXME: AddrLabelExpr (once we have cursors for labels)
381 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
382 bool VisitVAArgExpr(VAArgExpr *E);
383 // FIXME: InitListExpr (for the designators)
384 // FIXME: DesignatedInitExpr
Douglas Gregor94802292010-09-02 21:20:16 +0000385 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000386 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000387 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000388 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
389 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000390 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000391 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000392 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000393 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000394 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000395 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000396 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000397 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000398};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000399
Ted Kremenekab188932010-01-05 19:32:54 +0000400} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000401
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000402static SourceRange getRawCursorExtent(CXCursor C);
403
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000404RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000405 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
406}
407
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408/// \brief Visit the given cursor and, if requested by the visitor,
409/// its children.
410///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000411/// \param Cursor the cursor to visit.
412///
413/// \param CheckRegionOfInterest if true, then the caller already checked that
414/// this cursor is within the region of interest.
415///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000416/// \returns true if the visitation should be aborted, false if it
417/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000418bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000419 if (clang_isInvalid(Cursor.kind))
420 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000421
Douglas Gregorb1373d02010-01-20 20:59:29 +0000422 if (clang_isDeclaration(Cursor.kind)) {
423 Decl *D = getCursorDecl(Cursor);
424 assert(D && "Invalid declaration cursor");
425 if (D->getPCHLevel() > MaxPCHLevel)
426 return false;
427
428 if (D->isImplicit())
429 return false;
430 }
431
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000432 // If we have a range of interest, and this cursor doesn't intersect with it,
433 // we're done.
434 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000435 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000436 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000437 return false;
438 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000439
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440 switch (Visitor(Cursor, Parent, ClientData)) {
441 case CXChildVisit_Break:
442 return true;
443
444 case CXChildVisit_Continue:
445 return false;
446
447 case CXChildVisit_Recurse:
448 return VisitChildren(Cursor);
449 }
450
Douglas Gregorfd643772010-01-25 16:45:46 +0000451 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452}
453
Douglas Gregor788f5a12010-03-20 00:41:21 +0000454std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
455CursorVisitor::getPreprocessedEntities() {
456 PreprocessingRecord &PPRec
457 = *TU->getPreprocessor().getPreprocessingRecord();
458
459 bool OnlyLocalDecls
460 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
461
462 // There is no region of interest; we have to walk everything.
463 if (RegionOfInterest.isInvalid())
464 return std::make_pair(PPRec.begin(OnlyLocalDecls),
465 PPRec.end(OnlyLocalDecls));
466
467 // Find the file in which the region of interest lands.
468 SourceManager &SM = TU->getSourceManager();
469 std::pair<FileID, unsigned> Begin
470 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
471 std::pair<FileID, unsigned> End
472 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
473
474 // The region of interest spans files; we have to walk everything.
475 if (Begin.first != End.first)
476 return std::make_pair(PPRec.begin(OnlyLocalDecls),
477 PPRec.end(OnlyLocalDecls));
478
479 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
480 = TU->getPreprocessedEntitiesByFile();
481 if (ByFileMap.empty()) {
482 // Build the mapping from files to sets of preprocessed entities.
483 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
484 EEnd = PPRec.end(OnlyLocalDecls);
485 E != EEnd; ++E) {
486 std::pair<FileID, unsigned> P
487 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
488 ByFileMap[P.first].push_back(*E);
489 }
490 }
491
492 return std::make_pair(ByFileMap[Begin.first].begin(),
493 ByFileMap[Begin.first].end());
494}
495
Douglas Gregorb1373d02010-01-20 20:59:29 +0000496/// \brief Visit the children of the given cursor.
497///
498/// \returns true if the visitation should be aborted, false if it
499/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000500bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000501 if (clang_isReference(Cursor.kind)) {
502 // By definition, references have no children.
503 return false;
504 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000505
506 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000507 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000508 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000509
Douglas Gregorb1373d02010-01-20 20:59:29 +0000510 if (clang_isDeclaration(Cursor.kind)) {
511 Decl *D = getCursorDecl(Cursor);
512 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000513 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000514 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000515
Douglas Gregora59e3902010-01-21 23:27:09 +0000516 if (clang_isStatement(Cursor.kind))
517 return Visit(getCursorStmt(Cursor));
518 if (clang_isExpression(Cursor.kind))
519 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000520
Douglas Gregorb1373d02010-01-20 20:59:29 +0000521 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000522 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000523 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
524 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000525 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
526 TLEnd = CXXUnit->top_level_end();
527 TL != TLEnd; ++TL) {
528 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000529 return true;
530 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000531 } else if (VisitDeclContext(
532 CXXUnit->getASTContext().getTranslationUnitDecl()))
533 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000534
Douglas Gregor0396f462010-03-19 05:22:59 +0000535 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000536 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000537 // FIXME: Once we have the ability to deserialize a preprocessing record,
538 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000539 PreprocessingRecord::iterator E, EEnd;
540 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000541 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
542 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
543 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000544
Douglas Gregor0396f462010-03-19 05:22:59 +0000545 continue;
546 }
547
548 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
549 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
550 return true;
551
552 continue;
553 }
554 }
555 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000556 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000557 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000558
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000560 return false;
561}
562
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000563bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000564 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
565 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000566
Ted Kremenek664cffd2010-07-22 11:30:19 +0000567 if (Stmt *Body = B->getBody())
568 return Visit(MakeCXCursor(Body, StmtParent, TU));
569
570 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000571}
572
Douglas Gregorb1373d02010-01-20 20:59:29 +0000573bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000574 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000575 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000576
Ted Kremenek23173d72010-05-18 21:09:07 +0000577 Decl *D = *I;
578 if (D->getLexicalDeclContext() != DC)
579 continue;
580
581 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000582
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000583 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000584 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000585 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000586 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000587
588 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000589 case RangeBefore:
590 // This declaration comes before the region of interest; skip it.
591 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000592
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000593 case RangeAfter:
594 // This declaration comes after the region of interest; we're done.
595 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000596
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000597 case RangeOverlap:
598 // This declaration overlaps the region of interest; visit it.
599 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000600 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000601 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000602
Daniel Dunbard52864b2010-02-14 10:02:57 +0000603 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000604 return true;
605 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000606
Douglas Gregorb1373d02010-01-20 20:59:29 +0000607 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000608}
609
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000610bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
611 llvm_unreachable("Translation units are visited directly by Visit()");
612 return false;
613}
614
615bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
616 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
617 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000618
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000619 return false;
620}
621
622bool CursorVisitor::VisitTagDecl(TagDecl *D) {
623 return VisitDeclContext(D);
624}
625
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000626bool CursorVisitor::VisitClassTemplateSpecializationDecl(
627 ClassTemplateSpecializationDecl *D) {
628 bool ShouldVisitBody = false;
629 switch (D->getSpecializationKind()) {
630 case TSK_Undeclared:
631 case TSK_ImplicitInstantiation:
632 // Nothing to visit
633 return false;
634
635 case TSK_ExplicitInstantiationDeclaration:
636 case TSK_ExplicitInstantiationDefinition:
637 break;
638
639 case TSK_ExplicitSpecialization:
640 ShouldVisitBody = true;
641 break;
642 }
643
644 // Visit the template arguments used in the specialization.
645 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
646 TypeLoc TL = SpecType->getTypeLoc();
647 if (TemplateSpecializationTypeLoc *TSTLoc
648 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
649 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
650 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
651 return true;
652 }
653 }
654
655 if (ShouldVisitBody && VisitCXXRecordDecl(D))
656 return true;
657
658 return false;
659}
660
Douglas Gregor74dbe642010-08-31 19:31:58 +0000661bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
662 ClassTemplatePartialSpecializationDecl *D) {
663 // FIXME: Visit the "outer" template parameter lists on the TagDecl
664 // before visiting these template parameters.
665 if (VisitTemplateParameters(D->getTemplateParameters()))
666 return true;
667
668 // Visit the partial specialization arguments.
669 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
670 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
671 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
672 return true;
673
674 return VisitCXXRecordDecl(D);
675}
676
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000677bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000678 // Visit the default argument.
679 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
680 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
681 if (Visit(DefArg->getTypeLoc()))
682 return true;
683
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000684 return false;
685}
686
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000687bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
688 if (Expr *Init = D->getInitExpr())
689 return Visit(MakeCXCursor(Init, StmtParent, TU));
690 return false;
691}
692
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000693bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
694 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
695 if (Visit(TSInfo->getTypeLoc()))
696 return true;
697
698 return false;
699}
700
Douglas Gregora67e03f2010-09-09 21:42:20 +0000701/// \brief Compare two base or member initializers based on their source order.
702static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
703 CXXBaseOrMemberInitializer const * const *X
704 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
705 CXXBaseOrMemberInitializer const * const *Y
706 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
707
708 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
709 return -1;
710 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
711 return 1;
712 else
713 return 0;
714}
715
Douglas Gregorb1373d02010-01-20 20:59:29 +0000716bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000717 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
718 // Visit the function declaration's syntactic components in the order
719 // written. This requires a bit of work.
720 TypeLoc TL = TSInfo->getTypeLoc();
721 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
722
723 // If we have a function declared directly (without the use of a typedef),
724 // visit just the return type. Otherwise, just visit the function's type
725 // now.
726 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
727 (!FTL && Visit(TL)))
728 return true;
729
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000730 // Visit the nested-name-specifier, if present.
731 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
732 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
733 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000734
735 // Visit the declaration name.
736 if (VisitDeclarationNameInfo(ND->getNameInfo()))
737 return true;
738
739 // FIXME: Visit explicitly-specified template arguments!
740
741 // Visit the function parameters, if we have a function type.
742 if (FTL && VisitFunctionTypeLoc(*FTL, true))
743 return true;
744
745 // FIXME: Attributes?
746 }
747
Douglas Gregora67e03f2010-09-09 21:42:20 +0000748 if (ND->isThisDeclarationADefinition()) {
749 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
750 // Find the initializers that were written in the source.
751 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
752 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
753 IEnd = Constructor->init_end();
754 I != IEnd; ++I) {
755 if (!(*I)->isWritten())
756 continue;
757
758 WrittenInits.push_back(*I);
759 }
760
761 // Sort the initializers in source order
762 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
763 &CompareCXXBaseOrMemberInitializers);
764
765 // Visit the initializers in source order
766 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
767 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
768 if (Init->isMemberInitializer()) {
769 if (Visit(MakeCursorMemberRef(Init->getMember(),
770 Init->getMemberLocation(), TU)))
771 return true;
772 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
773 if (Visit(BaseInfo->getTypeLoc()))
774 return true;
775 }
776
777 // Visit the initializer value.
778 if (Expr *Initializer = Init->getInit())
779 if (Visit(MakeCXCursor(Initializer, ND, TU)))
780 return true;
781 }
782 }
783
784 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
785 return true;
786 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000787
Douglas Gregorb1373d02010-01-20 20:59:29 +0000788 return false;
789}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000790
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000791bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
792 if (VisitDeclaratorDecl(D))
793 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795 if (Expr *BitWidth = D->getBitWidth())
796 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000797
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000798 return false;
799}
800
801bool CursorVisitor::VisitVarDecl(VarDecl *D) {
802 if (VisitDeclaratorDecl(D))
803 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 if (Expr *Init = D->getInit())
806 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000807
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000808 return false;
809}
810
Douglas Gregor84b51d72010-09-01 20:16:53 +0000811bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
812 if (VisitDeclaratorDecl(D))
813 return true;
814
815 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
816 if (Expr *DefArg = D->getDefaultArgument())
817 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
818
819 return false;
820}
821
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000822bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
823 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
824 // before visiting these template parameters.
825 if (VisitTemplateParameters(D->getTemplateParameters()))
826 return true;
827
828 return VisitFunctionDecl(D->getTemplatedDecl());
829}
830
Douglas Gregor39d6f072010-08-31 19:02:00 +0000831bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
832 // FIXME: Visit the "outer" template parameter lists on the TagDecl
833 // before visiting these template parameters.
834 if (VisitTemplateParameters(D->getTemplateParameters()))
835 return true;
836
837 return VisitCXXRecordDecl(D->getTemplatedDecl());
838}
839
Douglas Gregor84b51d72010-09-01 20:16:53 +0000840bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
841 if (VisitTemplateParameters(D->getTemplateParameters()))
842 return true;
843
844 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
845 VisitTemplateArgumentLoc(D->getDefaultArgument()))
846 return true;
847
848 return false;
849}
850
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000851bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000852 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
853 if (Visit(TSInfo->getTypeLoc()))
854 return true;
855
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000856 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000857 PEnd = ND->param_end();
858 P != PEnd; ++P) {
859 if (Visit(MakeCXCursor(*P, TU)))
860 return true;
861 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000862
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000863 if (ND->isThisDeclarationADefinition() &&
864 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
865 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000866
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000867 return false;
868}
869
Douglas Gregora59e3902010-01-21 23:27:09 +0000870bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
871 return VisitDeclContext(D);
872}
873
Douglas Gregorb1373d02010-01-20 20:59:29 +0000874bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000875 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
876 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000877 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000878
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000879 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
880 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
881 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000882 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000883 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000884
Douglas Gregora59e3902010-01-21 23:27:09 +0000885 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000886}
887
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000888bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
889 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
890 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
891 E = PID->protocol_end(); I != E; ++I, ++PL)
892 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
893 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000894
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000895 return VisitObjCContainerDecl(PID);
896}
897
Ted Kremenek23173d72010-05-18 21:09:07 +0000898bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000899 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000900 return true;
901
Ted Kremenek23173d72010-05-18 21:09:07 +0000902 // FIXME: This implements a workaround with @property declarations also being
903 // installed in the DeclContext for the @interface. Eventually this code
904 // should be removed.
905 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
906 if (!CDecl || !CDecl->IsClassExtension())
907 return false;
908
909 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
910 if (!ID)
911 return false;
912
913 IdentifierInfo *PropertyId = PD->getIdentifier();
914 ObjCPropertyDecl *prevDecl =
915 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
916
917 if (!prevDecl)
918 return false;
919
920 // Visit synthesized methods since they will be skipped when visiting
921 // the @interface.
922 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
923 if (MD->isSynthesized())
924 if (Visit(MakeCXCursor(MD, TU)))
925 return true;
926
927 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
928 if (MD->isSynthesized())
929 if (Visit(MakeCXCursor(MD, TU)))
930 return true;
931
932 return false;
933}
934
Douglas Gregorb1373d02010-01-20 20:59:29 +0000935bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000936 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000937 if (D->getSuperClass() &&
938 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000939 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000940 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000941 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000942
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000943 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
944 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
945 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000946 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000947 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000948
Douglas Gregora59e3902010-01-21 23:27:09 +0000949 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000950}
951
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000952bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
953 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000954}
955
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000956bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000957 // 'ID' could be null when dealing with invalid code.
958 if (ObjCInterfaceDecl *ID = D->getClassInterface())
959 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
960 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000961
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000962 return VisitObjCImplDecl(D);
963}
964
965bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
966#if 0
967 // Issue callbacks for super class.
968 // FIXME: No source location information!
969 if (D->getSuperClass() &&
970 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000971 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000972 TU)))
973 return true;
974#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000975
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000976 return VisitObjCImplDecl(D);
977}
978
979bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
980 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
981 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
982 E = D->protocol_end();
983 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000984 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000985 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000986
987 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000988}
989
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000990bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
991 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
992 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
993 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000994
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000995 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000996}
997
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000998bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
999 return VisitDeclContext(D);
1000}
1001
Douglas Gregor69319002010-08-31 23:48:11 +00001002bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001003 // Visit nested-name-specifier.
1004 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1005 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1006 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001007
1008 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1009 D->getTargetNameLoc(), TU));
1010}
1011
Douglas Gregor7e242562010-09-01 19:52:22 +00001012bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001013 // Visit nested-name-specifier.
1014 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1015 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1016 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001017
1018 // FIXME: Provide a multi-reference of some kind for all of the declarations
1019 // that the using declaration refers to. We don't have this kind of cursor
1020 // yet.
1021
1022 return VisitDeclarationNameInfo(D->getNameInfo());
1023}
1024
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001025bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001026 // Visit nested-name-specifier.
1027 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1028 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1029 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001030
1031 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1032 D->getIdentLocation(), TU));
1033}
1034
Douglas Gregor7e242562010-09-01 19:52:22 +00001035bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001036 // Visit nested-name-specifier.
1037 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1038 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1039 return true;
1040
Douglas Gregor7e242562010-09-01 19:52:22 +00001041 return VisitDeclarationNameInfo(D->getNameInfo());
1042}
1043
1044bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1045 UnresolvedUsingTypenameDecl *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 false;
1052}
1053
Douglas Gregor01829d32010-08-31 14:41:23 +00001054bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1055 switch (Name.getName().getNameKind()) {
1056 case clang::DeclarationName::Identifier:
1057 case clang::DeclarationName::CXXLiteralOperatorName:
1058 case clang::DeclarationName::CXXOperatorName:
1059 case clang::DeclarationName::CXXUsingDirective:
1060 return false;
1061
1062 case clang::DeclarationName::CXXConstructorName:
1063 case clang::DeclarationName::CXXDestructorName:
1064 case clang::DeclarationName::CXXConversionFunctionName:
1065 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1066 return Visit(TSInfo->getTypeLoc());
1067 return false;
1068
1069 case clang::DeclarationName::ObjCZeroArgSelector:
1070 case clang::DeclarationName::ObjCOneArgSelector:
1071 case clang::DeclarationName::ObjCMultiArgSelector:
1072 // FIXME: Per-identifier location info?
1073 return false;
1074 }
1075
1076 return false;
1077}
1078
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001079bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1080 SourceRange Range) {
1081 // FIXME: This whole routine is a hack to work around the lack of proper
1082 // source information in nested-name-specifiers (PR5791). Since we do have
1083 // a beginning source location, we can visit the first component of the
1084 // nested-name-specifier, if it's a single-token component.
1085 if (!NNS)
1086 return false;
1087
1088 // Get the first component in the nested-name-specifier.
1089 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1090 NNS = Prefix;
1091
1092 switch (NNS->getKind()) {
1093 case NestedNameSpecifier::Namespace:
1094 // FIXME: The token at this source location might actually have been a
1095 // namespace alias, but we don't model that. Lame!
1096 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1097 TU));
1098
1099 case NestedNameSpecifier::TypeSpec: {
1100 // If the type has a form where we know that the beginning of the source
1101 // range matches up with a reference cursor. Visit the appropriate reference
1102 // cursor.
1103 Type *T = NNS->getAsType();
1104 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1105 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1106 if (const TagType *Tag = dyn_cast<TagType>(T))
1107 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1108 if (const TemplateSpecializationType *TST
1109 = dyn_cast<TemplateSpecializationType>(T))
1110 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1111 break;
1112 }
1113
1114 case NestedNameSpecifier::TypeSpecWithTemplate:
1115 case NestedNameSpecifier::Global:
1116 case NestedNameSpecifier::Identifier:
1117 break;
1118 }
1119
1120 return false;
1121}
1122
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001123bool CursorVisitor::VisitTemplateParameters(
1124 const TemplateParameterList *Params) {
1125 if (!Params)
1126 return false;
1127
1128 for (TemplateParameterList::const_iterator P = Params->begin(),
1129 PEnd = Params->end();
1130 P != PEnd; ++P) {
1131 if (Visit(MakeCXCursor(*P, TU)))
1132 return true;
1133 }
1134
1135 return false;
1136}
1137
Douglas Gregor0b36e612010-08-31 20:37:03 +00001138bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1139 switch (Name.getKind()) {
1140 case TemplateName::Template:
1141 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1142
1143 case TemplateName::OverloadedTemplate:
1144 // FIXME: We need a way to return multiple lookup results in a single
1145 // cursor.
1146 return false;
1147
1148 case TemplateName::DependentTemplate:
1149 // FIXME: Visit nested-name-specifier.
1150 return false;
1151
1152 case TemplateName::QualifiedTemplate:
1153 // FIXME: Visit nested-name-specifier.
1154 return Visit(MakeCursorTemplateRef(
1155 Name.getAsQualifiedTemplateName()->getDecl(),
1156 Loc, TU));
1157 }
1158
1159 return false;
1160}
1161
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001162bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1163 switch (TAL.getArgument().getKind()) {
1164 case TemplateArgument::Null:
1165 case TemplateArgument::Integral:
1166 return false;
1167
1168 case TemplateArgument::Pack:
1169 // FIXME: Implement when variadic templates come along.
1170 return false;
1171
1172 case TemplateArgument::Type:
1173 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1174 return Visit(TSInfo->getTypeLoc());
1175 return false;
1176
1177 case TemplateArgument::Declaration:
1178 if (Expr *E = TAL.getSourceDeclExpression())
1179 return Visit(MakeCXCursor(E, StmtParent, TU));
1180 return false;
1181
1182 case TemplateArgument::Expression:
1183 if (Expr *E = TAL.getSourceExpression())
1184 return Visit(MakeCXCursor(E, StmtParent, TU));
1185 return false;
1186
1187 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001188 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1189 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001190 }
1191
1192 return false;
1193}
1194
Ted Kremeneka0536d82010-05-07 01:04:29 +00001195bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1196 return VisitDeclContext(D);
1197}
1198
Douglas Gregor01829d32010-08-31 14:41:23 +00001199bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1200 return Visit(TL.getUnqualifiedLoc());
1201}
1202
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001203bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1204 ASTContext &Context = TU->getASTContext();
1205
1206 // Some builtin types (such as Objective-C's "id", "sel", and
1207 // "Class") have associated declarations. Create cursors for those.
1208 QualType VisitType;
1209 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001210 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001211 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001212 case BuiltinType::Char_U:
1213 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001214 case BuiltinType::Char16:
1215 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001216 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001217 case BuiltinType::UInt:
1218 case BuiltinType::ULong:
1219 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001220 case BuiltinType::UInt128:
1221 case BuiltinType::Char_S:
1222 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001223 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001224 case BuiltinType::Short:
1225 case BuiltinType::Int:
1226 case BuiltinType::Long:
1227 case BuiltinType::LongLong:
1228 case BuiltinType::Int128:
1229 case BuiltinType::Float:
1230 case BuiltinType::Double:
1231 case BuiltinType::LongDouble:
1232 case BuiltinType::NullPtr:
1233 case BuiltinType::Overload:
1234 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001235 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001236
1237 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001238 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001239
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001240 case BuiltinType::ObjCId:
1241 VisitType = Context.getObjCIdType();
1242 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001243
1244 case BuiltinType::ObjCClass:
1245 VisitType = Context.getObjCClassType();
1246 break;
1247
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001248 case BuiltinType::ObjCSel:
1249 VisitType = Context.getObjCSelType();
1250 break;
1251 }
1252
1253 if (!VisitType.isNull()) {
1254 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001255 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001256 TU));
1257 }
1258
1259 return false;
1260}
1261
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001262bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1263 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1264}
1265
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001266bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1267 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1268}
1269
1270bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1271 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1272}
1273
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001274bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1275 // FIXME: We can't visit the template template parameter, but there's
1276 // no context information with which we can match up the depth/index in the
1277 // type to the appropriate
1278 return false;
1279}
1280
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001281bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1282 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1283 return true;
1284
John McCallc12c5bb2010-05-15 11:32:37 +00001285 return false;
1286}
1287
1288bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1289 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1290 return true;
1291
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001292 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1293 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1294 TU)))
1295 return true;
1296 }
1297
1298 return false;
1299}
1300
1301bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001302 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001303}
1304
1305bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1306 return Visit(TL.getPointeeLoc());
1307}
1308
1309bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1310 return Visit(TL.getPointeeLoc());
1311}
1312
1313bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1314 return Visit(TL.getPointeeLoc());
1315}
1316
1317bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001318 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001319}
1320
1321bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001322 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001323}
1324
Douglas Gregor01829d32010-08-31 14:41:23 +00001325bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1326 bool SkipResultType) {
1327 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001328 return true;
1329
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001330 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001331 if (Decl *D = TL.getArg(I))
1332 if (Visit(MakeCXCursor(D, TU)))
1333 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001334
1335 return false;
1336}
1337
1338bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1339 if (Visit(TL.getElementLoc()))
1340 return true;
1341
1342 if (Expr *Size = TL.getSizeExpr())
1343 return Visit(MakeCXCursor(Size, StmtParent, TU));
1344
1345 return false;
1346}
1347
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001348bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1349 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001350 // Visit the template name.
1351 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1352 TL.getTemplateNameLoc()))
1353 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001354
1355 // Visit the template arguments.
1356 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1357 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1358 return true;
1359
1360 return false;
1361}
1362
Douglas Gregor2332c112010-01-21 20:48:56 +00001363bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1364 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1365}
1366
1367bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1368 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1369 return Visit(TSInfo->getTypeLoc());
1370
1371 return false;
1372}
1373
Douglas Gregora59e3902010-01-21 23:27:09 +00001374bool CursorVisitor::VisitStmt(Stmt *S) {
1375 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1376 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001377 if (Stmt *C = *Child)
1378 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1379 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001380 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001381
Douglas Gregora59e3902010-01-21 23:27:09 +00001382 return false;
1383}
1384
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001385bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1386 // Specially handle CaseStmts because they can be nested, e.g.:
1387 //
1388 // case 1:
1389 // case 2:
1390 //
1391 // In this case the second CaseStmt is the child of the first. Walking
1392 // these recursively can blow out the stack.
1393 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1394 while (true) {
1395 // Set the Parent field to Cursor, then back to its old value once we're
1396 // done.
1397 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1398
1399 if (Stmt *LHS = S->getLHS())
1400 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1401 return true;
1402 if (Stmt *RHS = S->getRHS())
1403 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1404 return true;
1405 if (Stmt *SubStmt = S->getSubStmt()) {
1406 if (!isa<CaseStmt>(SubStmt))
1407 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1408
1409 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1410 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1411 Cursor = MakeCXCursor(CS, StmtParent, TU);
1412 if (RegionOfInterest.isValid()) {
1413 SourceRange Range = CS->getSourceRange();
1414 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1415 return false;
1416 }
1417
1418 switch (Visitor(Cursor, Parent, ClientData)) {
1419 case CXChildVisit_Break: return true;
1420 case CXChildVisit_Continue: return false;
1421 case CXChildVisit_Recurse:
1422 // Perform tail-recursion manually.
1423 S = CS;
1424 continue;
1425 }
1426 }
1427 return false;
1428 }
1429}
1430
Douglas Gregora59e3902010-01-21 23:27:09 +00001431bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1432 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1433 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001434 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001435 return true;
1436 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001437
Douglas Gregora59e3902010-01-21 23:27:09 +00001438 return false;
1439}
1440
Douglas Gregorf5bab412010-01-22 01:00:11 +00001441bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1442 if (VarDecl *Var = S->getConditionVariable()) {
1443 if (Visit(MakeCXCursor(Var, TU)))
1444 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001445 }
1446
Douglas Gregor263b47b2010-01-25 16:12:32 +00001447 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1448 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001449 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1450 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001451 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1452 return true;
1453
1454 return false;
1455}
1456
1457bool CursorVisitor::VisitSwitchStmt(SwitchStmt *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;
1465 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1466 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001467
Douglas Gregor263b47b2010-01-25 16:12:32 +00001468 return false;
1469}
1470
1471bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1472 if (VarDecl *Var = S->getConditionVariable()) {
1473 if (Visit(MakeCXCursor(Var, TU)))
1474 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001475 }
1476
Douglas Gregor263b47b2010-01-25 16:12:32 +00001477 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1478 return true;
1479 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001480 return true;
1481
Douglas Gregor263b47b2010-01-25 16:12:32 +00001482 return false;
1483}
1484
1485bool CursorVisitor::VisitForStmt(ForStmt *S) {
1486 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1487 return true;
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->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1496 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001497 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1498 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001499
Douglas Gregorf5bab412010-01-22 01:00:11 +00001500 return false;
1501}
1502
Douglas Gregor8947a752010-09-02 20:35:02 +00001503bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1504 // Visit nested-name-specifier, if present.
1505 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1506 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1507 return true;
1508
1509 // Visit declaration name.
1510 if (VisitDeclarationNameInfo(E->getNameInfo()))
1511 return true;
1512
1513 // Visit explicitly-specified template arguments.
1514 if (E->hasExplicitTemplateArgs()) {
1515 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1516 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1517 *ArgEnd = Arg + Args.NumTemplateArgs;
1518 Arg != ArgEnd; ++Arg)
1519 if (VisitTemplateArgumentLoc(*Arg))
1520 return true;
1521 }
1522
1523 return false;
1524}
1525
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001526bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1527 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1528 return true;
1529
1530 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1531 return true;
1532
1533 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1534 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1535 return true;
1536
1537 return false;
1538}
1539
Ted Kremenek3064ef92010-08-27 21:34:58 +00001540bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1541 if (D->isDefinition()) {
1542 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1543 E = D->bases_end(); I != E; ++I) {
1544 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1545 return true;
1546 }
1547 }
1548
1549 return VisitTagDecl(D);
1550}
1551
1552
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001553bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1554 return Visit(B->getBlockDecl());
1555}
1556
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001557bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001558 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001559 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1560 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001561
1562 // Visit the components of the offsetof expression.
1563 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1564 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1565 const OffsetOfNode &Node = E->getComponent(I);
1566 switch (Node.getKind()) {
1567 case OffsetOfNode::Array:
1568 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1569 StmtParent, TU)))
1570 return true;
1571 break;
1572
1573 case OffsetOfNode::Field:
1574 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1575 TU)))
1576 return true;
1577 break;
1578
1579 case OffsetOfNode::Identifier:
1580 case OffsetOfNode::Base:
1581 continue;
1582 }
1583 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001584
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001585 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001586}
1587
Douglas Gregor336fd812010-01-23 00:40:08 +00001588bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1589 if (E->isArgumentType()) {
1590 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1591 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001592
Douglas Gregor336fd812010-01-23 00:40:08 +00001593 return false;
1594 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001595
Douglas Gregor336fd812010-01-23 00:40:08 +00001596 return VisitExpr(E);
1597}
1598
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001599bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1600 // Visit the base expression.
1601 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1602 return true;
1603
1604 // Visit the nested-name-specifier
1605 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1606 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1607 return true;
1608
1609 // Visit the declaration name.
1610 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1611 return true;
1612
1613 // Visit the explicitly-specified template arguments, if any.
1614 if (E->hasExplicitTemplateArgs()) {
1615 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1616 *ArgEnd = Arg + E->getNumTemplateArgs();
1617 Arg != ArgEnd;
1618 ++Arg) {
1619 if (VisitTemplateArgumentLoc(*Arg))
1620 return true;
1621 }
1622 }
1623
1624 return false;
1625}
1626
Douglas Gregor336fd812010-01-23 00:40:08 +00001627bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1628 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1629 if (Visit(TSInfo->getTypeLoc()))
1630 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001631
Douglas Gregor336fd812010-01-23 00:40:08 +00001632 return VisitCastExpr(E);
1633}
1634
1635bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1636 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1637 if (Visit(TSInfo->getTypeLoc()))
1638 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001639
Douglas Gregor336fd812010-01-23 00:40:08 +00001640 return VisitExpr(E);
1641}
1642
Douglas Gregor648220e2010-08-10 15:02:34 +00001643bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1644 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1645 Visit(E->getArgTInfo2()->getTypeLoc());
1646}
1647
1648bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1649 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1650 return true;
1651
1652 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1653}
1654
Douglas Gregor94802292010-09-02 21:20:16 +00001655bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1656 if (E->isTypeOperand()) {
1657 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1658 return Visit(TSInfo->getTypeLoc());
1659
1660 return false;
1661 }
1662
1663 return VisitExpr(E);
1664}
1665
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001666bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1667 if (E->isTypeOperand()) {
1668 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1669 return Visit(TSInfo->getTypeLoc());
1670
1671 return false;
1672 }
1673
1674 return VisitExpr(E);
1675}
1676
Douglas Gregorab6677e2010-09-08 00:15:04 +00001677bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1678 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1679 return Visit(TSInfo->getTypeLoc());
1680
1681 return VisitExpr(E);
1682}
1683
1684bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1685 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1686 return Visit(TSInfo->getTypeLoc());
1687
1688 return false;
1689}
1690
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001691bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1692 // Visit placement arguments.
1693 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1694 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1695 return true;
1696
1697 // Visit the allocated type.
1698 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1699 if (Visit(TSInfo->getTypeLoc()))
1700 return true;
1701
1702 // Visit the array size, if any.
1703 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1704 return true;
1705
1706 // Visit the initializer or constructor arguments.
1707 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1708 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1709 return true;
1710
1711 return false;
1712}
1713
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001714bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1715 // Visit base expression.
1716 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1717 return true;
1718
1719 // Visit the nested-name-specifier.
1720 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1721 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1722 return true;
1723
1724 // Visit the scope type that looks disturbingly like the nested-name-specifier
1725 // but isn't.
1726 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1727 if (Visit(TSInfo->getTypeLoc()))
1728 return true;
1729
1730 // Visit the name of the type being destroyed.
1731 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1732 if (Visit(TSInfo->getTypeLoc()))
1733 return true;
1734
1735 return false;
1736}
1737
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001738bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1739 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1740}
1741
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001742bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001743 // Visit the nested-name-specifier.
1744 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1745 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1746 return true;
1747
1748 // Visit the declaration name.
1749 if (VisitDeclarationNameInfo(E->getNameInfo()))
1750 return true;
1751
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001752 // Visit the explicitly-specified template arguments.
1753 if (const ExplicitTemplateArgumentList *ArgList
1754 = E->getOptionalExplicitTemplateArgs()) {
1755 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1756 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1757 Arg != ArgEnd; ++Arg) {
1758 if (VisitTemplateArgumentLoc(*Arg))
1759 return true;
1760 }
1761 }
1762
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001763 // FIXME: We don't have a way to visit all of the declarations referenced
1764 // here.
1765 return false;
1766}
1767
Douglas Gregorbfebed22010-09-03 17:24:10 +00001768bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1769 DependentScopeDeclRefExpr *E) {
1770 // Visit the nested-name-specifier.
1771 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1772 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1773 return true;
1774
1775 // Visit the declaration name.
1776 if (VisitDeclarationNameInfo(E->getNameInfo()))
1777 return true;
1778
1779 // Visit the explicitly-specified template arguments.
1780 if (const ExplicitTemplateArgumentList *ArgList
1781 = E->getOptionalExplicitTemplateArgs()) {
1782 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1783 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1784 Arg != ArgEnd; ++Arg) {
1785 if (VisitTemplateArgumentLoc(*Arg))
1786 return true;
1787 }
1788 }
1789
1790 return false;
1791}
1792
Douglas Gregorab6677e2010-09-08 00:15:04 +00001793bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1794 CXXUnresolvedConstructExpr *E) {
1795 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1796 if (Visit(TSInfo->getTypeLoc()))
1797 return true;
1798
1799 return VisitExpr(E);
1800}
1801
Douglas Gregor25d63622010-09-03 17:35:34 +00001802bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1803 CXXDependentScopeMemberExpr *E) {
1804 // Visit the base expression, if there is one.
1805 if (!E->isImplicitAccess() &&
1806 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1807 return true;
1808
1809 // Visit the nested-name-specifier.
1810 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1811 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1812 return true;
1813
1814 // Visit the declaration name.
1815 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1816 return true;
1817
1818 // Visit the explicitly-specified template arguments.
1819 if (const ExplicitTemplateArgumentList *ArgList
1820 = E->getOptionalExplicitTemplateArgs()) {
1821 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1822 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1823 Arg != ArgEnd; ++Arg) {
1824 if (VisitTemplateArgumentLoc(*Arg))
1825 return true;
1826 }
1827 }
1828
1829 return false;
1830}
1831
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001832bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1833 // Visit the base expression, if there is one.
1834 if (!E->isImplicitAccess() &&
1835 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1836 return true;
1837
1838 return VisitOverloadExpr(E);
1839}
Douglas Gregor25d63622010-09-03 17:35:34 +00001840
Douglas Gregorc2350e52010-03-08 16:40:19 +00001841bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001842 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1843 if (Visit(TSInfo->getTypeLoc()))
1844 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001845
1846 return VisitExpr(E);
1847}
1848
Douglas Gregor81d34662010-04-20 15:39:42 +00001849bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1850 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1851}
1852
1853
Ted Kremenek09dfa372010-02-18 05:46:33 +00001854bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001855 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1856 i != e; ++i)
1857 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001858 return true;
1859
1860 return false;
1861}
1862
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001863extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001864CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1865 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001866 // We use crash recovery to make some of our APIs more reliable, implicitly
1867 // enable it.
1868 llvm::CrashRecoveryContext::Enable();
1869
Douglas Gregora030b7c2010-01-22 20:35:53 +00001870 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001871 if (excludeDeclarationsFromPCH)
1872 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001873 if (displayDiagnostics)
1874 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001875 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001876}
1877
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001878void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001879 if (CIdx)
1880 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001881 if (getenv("LIBCLANG_TIMING"))
1882 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001883}
1884
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001885void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001886 if (CIdx) {
1887 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1888 CXXIdx->setUseExternalASTGeneration(value);
1889 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001890}
1891
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001892CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001893 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001894 if (!CIdx)
1895 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001896
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001897 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001898
Douglas Gregor28019772010-04-05 23:52:57 +00001899 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001900 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001901 CXXIdx->getOnlyLocalDecls(),
1902 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001903}
1904
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001905unsigned clang_defaultEditingTranslationUnitOptions() {
1906 return CXTranslationUnit_PrecompiledPreamble;
1907}
1908
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001909CXTranslationUnit
1910clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1911 const char *source_filename,
1912 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001913 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001914 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001915 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001916 return clang_parseTranslationUnit(CIdx, source_filename,
1917 command_line_args, num_command_line_args,
1918 unsaved_files, num_unsaved_files,
1919 CXTranslationUnit_DetailedPreprocessingRecord);
1920}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001921
1922struct ParseTranslationUnitInfo {
1923 CXIndex CIdx;
1924 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001925 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001926 int num_command_line_args;
1927 struct CXUnsavedFile *unsaved_files;
1928 unsigned num_unsaved_files;
1929 unsigned options;
1930 CXTranslationUnit result;
1931};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001932static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001933 ParseTranslationUnitInfo *PTUI =
1934 static_cast<ParseTranslationUnitInfo*>(UserData);
1935 CXIndex CIdx = PTUI->CIdx;
1936 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001937 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001938 int num_command_line_args = PTUI->num_command_line_args;
1939 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1940 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1941 unsigned options = PTUI->options;
1942 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001943
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001944 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001945 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001946
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001947 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1948
Douglas Gregor44c181a2010-07-23 00:33:23 +00001949 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001950 bool CompleteTranslationUnit
1951 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001952 bool CacheCodeCompetionResults
1953 = options & CXTranslationUnit_CacheCompletionResults;
1954
Douglas Gregor5352ac02010-01-28 00:27:43 +00001955 // Configure the diagnostics.
1956 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001957 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1958 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001959
Douglas Gregor4db64a42010-01-23 00:14:00 +00001960 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1961 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001962 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001963 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001964 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001965 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1966 Buffer));
1967 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001968
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001969 if (!CXXIdx->getUseExternalASTGeneration()) {
1970 llvm::SmallVector<const char *, 16> Args;
1971
1972 // The 'source_filename' argument is optional. If the caller does not
1973 // specify it then it is assumed that the source file is specified
1974 // in the actual argument list.
1975 if (source_filename)
1976 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001977
1978 // Since the Clang C library is primarily used by batch tools dealing with
1979 // (often very broken) source code, where spell-checking can have a
1980 // significant negative impact on performance (particularly when
1981 // precompiled headers are involved), we disable it by default.
1982 // Note that we place this argument early in the list, so that it can be
1983 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001984 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001985
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001986 Args.insert(Args.end(), command_line_args,
1987 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001988
Douglas Gregor44c181a2010-07-23 00:33:23 +00001989 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001990 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1991 Args.push_back("-Xclang");
1992 Args.push_back("-detailed-preprocessing-record");
1993 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001994
Douglas Gregor5352ac02010-01-28 00:27:43 +00001995 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001996
Ted Kremenek29b72842010-01-07 22:49:05 +00001997#ifdef USE_CRASHTRACER
1998 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001999#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002000
Daniel Dunbar94220972009-12-05 02:17:18 +00002001 llvm::OwningPtr<ASTUnit> Unit(
2002 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00002003 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00002004 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00002005 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00002006 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00002007 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00002008 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00002009 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00002010 CompleteTranslationUnit,
2011 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002012
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002013 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00002014 // Make sure to check that 'Unit' is non-NULL.
2015 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00002016 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2017 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002018 D != DEnd; ++D) {
2019 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00002020 CXString Msg = clang_formatDiagnostic(&Diag,
2021 clang_defaultDiagnosticDisplayOptions());
2022 fprintf(stderr, "%s\n", clang_getCString(Msg));
2023 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002024 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002025#ifdef LLVM_ON_WIN32
2026 // On Windows, force a flush, since there may be multiple copies of
2027 // stderr and stdout in the file system, all with different buffers
2028 // but writing to the same device.
2029 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00002030#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002031 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002032 }
Daniel Dunbar94220972009-12-05 02:17:18 +00002033
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002034 PTUI->result = Unit.take();
2035 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00002036 }
2037
Ted Kremenek139ba862009-10-22 00:03:57 +00002038 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002039 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002040
Ted Kremenek139ba862009-10-22 00:03:57 +00002041 // First add the complete path to the 'clang' executable.
2042 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002043 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002044
Ted Kremenek139ba862009-10-22 00:03:57 +00002045 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002046 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002047
Ted Kremenek139ba862009-10-22 00:03:57 +00002048 // The 'source_filename' argument is optional. If the caller does not
2049 // specify it then it is assumed that the source file is specified
2050 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002051 if (source_filename)
2052 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00002053
Steve Naroff37b5ac22009-10-15 20:50:09 +00002054 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00002055 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00002056 char astTmpFile[L_tmpnam];
2057 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002058
2059 // Since the Clang C library is primarily used by batch tools dealing with
2060 // (often very broken) source code, where spell-checking can have a
2061 // significant negative impact on performance (particularly when
2062 // precompiled headers are involved), we disable it by default.
2063 // Note that we place this argument early in the list, so that it can be
2064 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00002065 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00002066
Douglas Gregor4db64a42010-01-23 00:14:00 +00002067 // Remap any unsaved files to temporary files.
2068 std::vector<llvm::sys::Path> TemporaryFiles;
2069 std::vector<std::string> RemapArgs;
2070 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002071 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002072
Douglas Gregor4db64a42010-01-23 00:14:00 +00002073 // The pointers into the elements of RemapArgs are stable because we
2074 // won't be adding anything to RemapArgs after this point.
2075 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
2076 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002077
Ted Kremenek139ba862009-10-22 00:03:57 +00002078 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
2079 for (int i = 0; i < num_command_line_args; ++i)
2080 if (const char *arg = command_line_args[i]) {
2081 if (strcmp(arg, "-o") == 0) {
2082 ++i; // Also skip the matching argument.
2083 continue;
2084 }
2085 if (strcmp(arg, "-emit-ast") == 0 ||
2086 strcmp(arg, "-c") == 0 ||
2087 strcmp(arg, "-fsyntax-only") == 0) {
2088 continue;
2089 }
2090
2091 // Keep the argument.
2092 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002093 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002094
Douglas Gregord93256e2010-01-28 06:00:51 +00002095 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00002096 char tmpFileResults[L_tmpnam];
2097 char *tmpResultsFileName = tmpnam(tmpFileResults);
2098 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00002099 TemporaryFiles.push_back(DiagnosticsFile);
2100 argv.push_back("-fdiagnostics-binary");
2101
Douglas Gregor44c181a2010-07-23 00:33:23 +00002102 // Do we need the detailed preprocessing record?
2103 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2104 argv.push_back("-Xclang");
2105 argv.push_back("-detailed-preprocessing-record");
2106 }
2107
Ted Kremenek139ba862009-10-22 00:03:57 +00002108 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00002109 argv.push_back(NULL);
2110
Ted Kremenekfeb15e32009-10-26 22:14:08 +00002111 // Invoke 'clang'.
2112 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
2113 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00002114 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00002115 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
2116 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00002117 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002118 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00002119 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002120
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002121 if (!ErrMsg.empty()) {
2122 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00002123 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002124 I != E; ++I) {
2125 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00002126 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00002127 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00002128 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002129
Daniel Dunbar32141c82010-02-23 20:23:45 +00002130 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00002131 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00002132
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002133 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002134 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00002135 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00002136 RemappedFiles.size(),
2137 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00002138 if (ATU) {
2139 LoadSerializedDiagnostics(DiagnosticsFile,
2140 num_unsaved_files, unsaved_files,
2141 ATU->getFileManager(),
2142 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00002143 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002144 } else if (CXXIdx->getDisplayDiagnostics()) {
2145 // We failed to load the ASTUnit, but we can still deserialize the
2146 // diagnostics and emit them.
2147 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00002148 Diagnostic Diag;
2149 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002150 // FIXME: Faked LangOpts!
2151 LangOptions LangOpts;
2152 llvm::SmallVector<StoredDiagnostic, 4> Diags;
2153 LoadSerializedDiagnostics(DiagnosticsFile,
2154 num_unsaved_files, unsaved_files,
2155 FileMgr, SourceMgr, Diags);
2156 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
2157 DEnd = Diags.end();
2158 D != DEnd; ++D) {
2159 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00002160 CXString Msg = clang_formatDiagnostic(&Diag,
2161 clang_defaultDiagnosticDisplayOptions());
2162 fprintf(stderr, "%s\n", clang_getCString(Msg));
2163 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002164 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002165
2166#ifdef LLVM_ON_WIN32
2167 // On Windows, force a flush, since there may be multiple copies of
2168 // stderr and stdout in the file system, all with different buffers
2169 // but writing to the same device.
2170 fflush(stderr);
2171#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00002172 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002173
Douglas Gregor313e26c2010-02-18 23:35:40 +00002174 if (ATU) {
2175 // Make the translation unit responsible for destroying all temporary files.
2176 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2177 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002178 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00002179 } else {
2180 // Destroy all of the temporary files now; they can't be referenced any
2181 // longer.
2182 llvm::sys::Path(astTmpFile).eraseFromDisk();
2183 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2184 TemporaryFiles[i].eraseFromDisk();
2185 }
2186
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002187 PTUI->result = ATU;
2188}
2189CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2190 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002191 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002192 int num_command_line_args,
2193 struct CXUnsavedFile *unsaved_files,
2194 unsigned num_unsaved_files,
2195 unsigned options) {
2196 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2197 num_command_line_args, unsaved_files, num_unsaved_files,
2198 options, 0 };
2199 llvm::CrashRecoveryContext CRC;
2200
2201 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002202 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2203 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2204 fprintf(stderr, " 'command_line_args' : [");
2205 for (int i = 0; i != num_command_line_args; ++i) {
2206 if (i)
2207 fprintf(stderr, ", ");
2208 fprintf(stderr, "'%s'", command_line_args[i]);
2209 }
2210 fprintf(stderr, "],\n");
2211 fprintf(stderr, " 'unsaved_files' : [");
2212 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2213 if (i)
2214 fprintf(stderr, ", ");
2215 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2216 unsaved_files[i].Length);
2217 }
2218 fprintf(stderr, "],\n");
2219 fprintf(stderr, " 'options' : %d,\n", options);
2220 fprintf(stderr, "}\n");
2221
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002222 return 0;
2223 }
2224
2225 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002226}
2227
Douglas Gregor19998442010-08-13 15:35:05 +00002228unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2229 return CXSaveTranslationUnit_None;
2230}
2231
2232int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2233 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002234 if (!TU)
2235 return 1;
2236
2237 return static_cast<ASTUnit *>(TU)->Save(FileName);
2238}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002239
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002240void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002241 if (CTUnit) {
2242 // If the translation unit has been marked as unsafe to free, just discard
2243 // it.
2244 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2245 return;
2246
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002247 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002248 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002249}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002250
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002251unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2252 return CXReparse_None;
2253}
2254
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002255struct ReparseTranslationUnitInfo {
2256 CXTranslationUnit TU;
2257 unsigned num_unsaved_files;
2258 struct CXUnsavedFile *unsaved_files;
2259 unsigned options;
2260 int result;
2261};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002262static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002263 ReparseTranslationUnitInfo *RTUI =
2264 static_cast<ReparseTranslationUnitInfo*>(UserData);
2265 CXTranslationUnit TU = RTUI->TU;
2266 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2267 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2268 unsigned options = RTUI->options;
2269 (void) options;
2270 RTUI->result = 1;
2271
Douglas Gregorabc563f2010-07-19 21:46:24 +00002272 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002273 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002274
2275 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2276 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2277 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2278 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002279 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002280 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2281 Buffer));
2282 }
2283
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002284 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
2285 RemappedFiles.size()))
2286 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002287}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002288int clang_reparseTranslationUnit(CXTranslationUnit TU,
2289 unsigned num_unsaved_files,
2290 struct CXUnsavedFile *unsaved_files,
2291 unsigned options) {
2292 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2293 options, 0 };
2294 llvm::CrashRecoveryContext CRC;
2295
2296 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002297 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002298 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2299 return 1;
2300 }
2301
2302 return RTUI.result;
2303}
2304
Douglas Gregordf95a132010-08-09 20:45:32 +00002305
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002306CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002307 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002308 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002309
Steve Naroff77accc12009-09-03 18:19:54 +00002310 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002311 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002312}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002313
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002314CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002315 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002316 return Result;
2317}
2318
Ted Kremenekfb480492010-01-13 21:46:36 +00002319} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002320
Ted Kremenekfb480492010-01-13 21:46:36 +00002321//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002322// CXSourceLocation and CXSourceRange Operations.
2323//===----------------------------------------------------------------------===//
2324
Douglas Gregorb9790342010-01-22 21:44:22 +00002325extern "C" {
2326CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002327 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002328 return Result;
2329}
2330
2331unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002332 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2333 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2334 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002335}
2336
2337CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2338 CXFile file,
2339 unsigned line,
2340 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002341 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002342 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002343
Douglas Gregorb9790342010-01-22 21:44:22 +00002344 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2345 SourceLocation SLoc
2346 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002347 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002348 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002349
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002350 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002351}
2352
Douglas Gregor5352ac02010-01-28 00:27:43 +00002353CXSourceRange clang_getNullRange() {
2354 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2355 return Result;
2356}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002357
Douglas Gregor5352ac02010-01-28 00:27:43 +00002358CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2359 if (begin.ptr_data[0] != end.ptr_data[0] ||
2360 begin.ptr_data[1] != end.ptr_data[1])
2361 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002362
2363 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002364 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002365 return Result;
2366}
2367
Douglas Gregor46766dc2010-01-26 19:19:08 +00002368void clang_getInstantiationLocation(CXSourceLocation location,
2369 CXFile *file,
2370 unsigned *line,
2371 unsigned *column,
2372 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002373 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2374
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002375 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002376 if (file)
2377 *file = 0;
2378 if (line)
2379 *line = 0;
2380 if (column)
2381 *column = 0;
2382 if (offset)
2383 *offset = 0;
2384 return;
2385 }
2386
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002387 const SourceManager &SM =
2388 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002389 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002390
2391 if (file)
2392 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2393 if (line)
2394 *line = SM.getInstantiationLineNumber(InstLoc);
2395 if (column)
2396 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002397 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002398 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002399}
2400
Douglas Gregor1db19de2010-01-19 21:36:55 +00002401CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002402 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002403 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002404 return Result;
2405}
2406
2407CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002408 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002409 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002410 return Result;
2411}
2412
Douglas Gregorb9790342010-01-22 21:44:22 +00002413} // end: extern "C"
2414
Douglas Gregor1db19de2010-01-19 21:36:55 +00002415//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002416// CXFile Operations.
2417//===----------------------------------------------------------------------===//
2418
2419extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002420CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002421 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002422 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002423
Steve Naroff88145032009-10-27 14:35:18 +00002424 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002425 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002426}
2427
2428time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002429 if (!SFile)
2430 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002431
Steve Naroff88145032009-10-27 14:35:18 +00002432 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2433 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002434}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002435
Douglas Gregorb9790342010-01-22 21:44:22 +00002436CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2437 if (!tu)
2438 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002439
Douglas Gregorb9790342010-01-22 21:44:22 +00002440 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002441
Douglas Gregorb9790342010-01-22 21:44:22 +00002442 FileManager &FMgr = CXXUnit->getFileManager();
2443 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2444 return const_cast<FileEntry *>(File);
2445}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002446
Ted Kremenekfb480492010-01-13 21:46:36 +00002447} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002448
Ted Kremenekfb480492010-01-13 21:46:36 +00002449//===----------------------------------------------------------------------===//
2450// CXCursor Operations.
2451//===----------------------------------------------------------------------===//
2452
Ted Kremenekfb480492010-01-13 21:46:36 +00002453static Decl *getDeclFromExpr(Stmt *E) {
2454 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2455 return RefExpr->getDecl();
2456 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2457 return ME->getMemberDecl();
2458 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2459 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002460
Ted Kremenekfb480492010-01-13 21:46:36 +00002461 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2462 return getDeclFromExpr(CE->getCallee());
2463 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2464 return getDeclFromExpr(CE->getSubExpr());
2465 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2466 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002467
Ted Kremenekfb480492010-01-13 21:46:36 +00002468 return 0;
2469}
2470
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002471static SourceLocation getLocationFromExpr(Expr *E) {
2472 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2473 return /*FIXME:*/Msg->getLeftLoc();
2474 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2475 return DRE->getLocation();
2476 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2477 return Member->getMemberLoc();
2478 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2479 return Ivar->getLocation();
2480 return E->getLocStart();
2481}
2482
Ted Kremenekfb480492010-01-13 21:46:36 +00002483extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002484
2485unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002486 CXCursorVisitor visitor,
2487 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002488 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002489
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002490 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2491 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002492 return CursorVis.VisitChildren(parent);
2493}
2494
Douglas Gregor78205d42010-01-20 21:45:58 +00002495static CXString getDeclSpelling(Decl *D) {
2496 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2497 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002498 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002499
Douglas Gregor78205d42010-01-20 21:45:58 +00002500 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002501 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002502
Douglas Gregor78205d42010-01-20 21:45:58 +00002503 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2504 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2505 // and returns different names. NamedDecl returns the class name and
2506 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002507 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002508
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002509 if (isa<UsingDirectiveDecl>(D))
2510 return createCXString("");
2511
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002512 llvm::SmallString<1024> S;
2513 llvm::raw_svector_ostream os(S);
2514 ND->printName(os);
2515
2516 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002517}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002518
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002519CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002520 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002521 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002522
Steve Narofff334b4e2009-09-02 18:26:48 +00002523 if (clang_isReference(C.kind)) {
2524 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002525 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002526 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002527 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002528 }
2529 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002530 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002531 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002532 }
2533 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002534 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002535 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002536 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002537 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002538 case CXCursor_CXXBaseSpecifier: {
2539 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2540 return createCXString(B->getType().getAsString());
2541 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002542 case CXCursor_TypeRef: {
2543 TypeDecl *Type = getCursorTypeRef(C).first;
2544 assert(Type && "Missing type decl");
2545
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002546 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2547 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002548 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002549 case CXCursor_TemplateRef: {
2550 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002551 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002552
2553 return createCXString(Template->getNameAsString());
2554 }
Douglas Gregor69319002010-08-31 23:48:11 +00002555
2556 case CXCursor_NamespaceRef: {
2557 NamedDecl *NS = getCursorNamespaceRef(C).first;
2558 assert(NS && "Missing namespace decl");
2559
2560 return createCXString(NS->getNameAsString());
2561 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002562
Douglas Gregora67e03f2010-09-09 21:42:20 +00002563 case CXCursor_MemberRef: {
2564 FieldDecl *Field = getCursorMemberRef(C).first;
2565 assert(Field && "Missing member decl");
2566
2567 return createCXString(Field->getNameAsString());
2568 }
2569
Daniel Dunbaracca7252009-11-30 20:42:49 +00002570 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002571 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002572 }
2573 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002574
2575 if (clang_isExpression(C.kind)) {
2576 Decl *D = getDeclFromExpr(getCursorExpr(C));
2577 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002578 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002579 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002580 }
2581
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002582 if (C.kind == CXCursor_MacroInstantiation)
2583 return createCXString(getCursorMacroInstantiation(C)->getName()
2584 ->getNameStart());
2585
Douglas Gregor572feb22010-03-18 18:04:21 +00002586 if (C.kind == CXCursor_MacroDefinition)
2587 return createCXString(getCursorMacroDefinition(C)->getName()
2588 ->getNameStart());
2589
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002590 if (clang_isDeclaration(C.kind))
2591 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002592
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002593 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002594}
2595
Ted Kremeneke68fff62010-02-17 00:41:32 +00002596CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002597 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002598 case CXCursor_FunctionDecl:
2599 return createCXString("FunctionDecl");
2600 case CXCursor_TypedefDecl:
2601 return createCXString("TypedefDecl");
2602 case CXCursor_EnumDecl:
2603 return createCXString("EnumDecl");
2604 case CXCursor_EnumConstantDecl:
2605 return createCXString("EnumConstantDecl");
2606 case CXCursor_StructDecl:
2607 return createCXString("StructDecl");
2608 case CXCursor_UnionDecl:
2609 return createCXString("UnionDecl");
2610 case CXCursor_ClassDecl:
2611 return createCXString("ClassDecl");
2612 case CXCursor_FieldDecl:
2613 return createCXString("FieldDecl");
2614 case CXCursor_VarDecl:
2615 return createCXString("VarDecl");
2616 case CXCursor_ParmDecl:
2617 return createCXString("ParmDecl");
2618 case CXCursor_ObjCInterfaceDecl:
2619 return createCXString("ObjCInterfaceDecl");
2620 case CXCursor_ObjCCategoryDecl:
2621 return createCXString("ObjCCategoryDecl");
2622 case CXCursor_ObjCProtocolDecl:
2623 return createCXString("ObjCProtocolDecl");
2624 case CXCursor_ObjCPropertyDecl:
2625 return createCXString("ObjCPropertyDecl");
2626 case CXCursor_ObjCIvarDecl:
2627 return createCXString("ObjCIvarDecl");
2628 case CXCursor_ObjCInstanceMethodDecl:
2629 return createCXString("ObjCInstanceMethodDecl");
2630 case CXCursor_ObjCClassMethodDecl:
2631 return createCXString("ObjCClassMethodDecl");
2632 case CXCursor_ObjCImplementationDecl:
2633 return createCXString("ObjCImplementationDecl");
2634 case CXCursor_ObjCCategoryImplDecl:
2635 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002636 case CXCursor_CXXMethod:
2637 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002638 case CXCursor_UnexposedDecl:
2639 return createCXString("UnexposedDecl");
2640 case CXCursor_ObjCSuperClassRef:
2641 return createCXString("ObjCSuperClassRef");
2642 case CXCursor_ObjCProtocolRef:
2643 return createCXString("ObjCProtocolRef");
2644 case CXCursor_ObjCClassRef:
2645 return createCXString("ObjCClassRef");
2646 case CXCursor_TypeRef:
2647 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002648 case CXCursor_TemplateRef:
2649 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002650 case CXCursor_NamespaceRef:
2651 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002652 case CXCursor_MemberRef:
2653 return createCXString("MemberRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002654 case CXCursor_UnexposedExpr:
2655 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002656 case CXCursor_BlockExpr:
2657 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002658 case CXCursor_DeclRefExpr:
2659 return createCXString("DeclRefExpr");
2660 case CXCursor_MemberRefExpr:
2661 return createCXString("MemberRefExpr");
2662 case CXCursor_CallExpr:
2663 return createCXString("CallExpr");
2664 case CXCursor_ObjCMessageExpr:
2665 return createCXString("ObjCMessageExpr");
2666 case CXCursor_UnexposedStmt:
2667 return createCXString("UnexposedStmt");
2668 case CXCursor_InvalidFile:
2669 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002670 case CXCursor_InvalidCode:
2671 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002672 case CXCursor_NoDeclFound:
2673 return createCXString("NoDeclFound");
2674 case CXCursor_NotImplemented:
2675 return createCXString("NotImplemented");
2676 case CXCursor_TranslationUnit:
2677 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002678 case CXCursor_UnexposedAttr:
2679 return createCXString("UnexposedAttr");
2680 case CXCursor_IBActionAttr:
2681 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002682 case CXCursor_IBOutletAttr:
2683 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002684 case CXCursor_IBOutletCollectionAttr:
2685 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002686 case CXCursor_PreprocessingDirective:
2687 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002688 case CXCursor_MacroDefinition:
2689 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002690 case CXCursor_MacroInstantiation:
2691 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002692 case CXCursor_Namespace:
2693 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002694 case CXCursor_LinkageSpec:
2695 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002696 case CXCursor_CXXBaseSpecifier:
2697 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002698 case CXCursor_Constructor:
2699 return createCXString("CXXConstructor");
2700 case CXCursor_Destructor:
2701 return createCXString("CXXDestructor");
2702 case CXCursor_ConversionFunction:
2703 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002704 case CXCursor_TemplateTypeParameter:
2705 return createCXString("TemplateTypeParameter");
2706 case CXCursor_NonTypeTemplateParameter:
2707 return createCXString("NonTypeTemplateParameter");
2708 case CXCursor_TemplateTemplateParameter:
2709 return createCXString("TemplateTemplateParameter");
2710 case CXCursor_FunctionTemplate:
2711 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002712 case CXCursor_ClassTemplate:
2713 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002714 case CXCursor_ClassTemplatePartialSpecialization:
2715 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002716 case CXCursor_NamespaceAlias:
2717 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002718 case CXCursor_UsingDirective:
2719 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002720 case CXCursor_UsingDeclaration:
2721 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002722 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002723
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002724 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002725 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002726}
Steve Naroff89922f82009-08-31 00:59:03 +00002727
Ted Kremeneke68fff62010-02-17 00:41:32 +00002728enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2729 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002730 CXClientData client_data) {
2731 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2732 *BestCursor = cursor;
2733 return CXChildVisit_Recurse;
2734}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002735
Douglas Gregorb9790342010-01-22 21:44:22 +00002736CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2737 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002738 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002739
Douglas Gregorb9790342010-01-22 21:44:22 +00002740 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002741 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2742
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002743 // Translate the given source location to make it point at the beginning of
2744 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002745 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002746
2747 // Guard against an invalid SourceLocation, or we may assert in one
2748 // of the following calls.
2749 if (SLoc.isInvalid())
2750 return clang_getNullCursor();
2751
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002752 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2753 CXXUnit->getASTContext().getLangOptions());
2754
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002755 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2756 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002757 // FIXME: Would be great to have a "hint" cursor, then walk from that
2758 // hint cursor upward until we find a cursor whose source range encloses
2759 // the region of interest, rather than starting from the translation unit.
2760 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002761 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002762 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002763 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002764 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002765 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002766}
2767
Ted Kremenek73885552009-11-17 19:28:59 +00002768CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002769 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002770}
2771
2772unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002773 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002774}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002775
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002776unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002777 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2778}
2779
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002780unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002781 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2782}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002783
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002784unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002785 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2786}
2787
Douglas Gregor97b98722010-01-19 23:20:36 +00002788unsigned clang_isExpression(enum CXCursorKind K) {
2789 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2790}
2791
2792unsigned clang_isStatement(enum CXCursorKind K) {
2793 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2794}
2795
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002796unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2797 return K == CXCursor_TranslationUnit;
2798}
2799
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002800unsigned clang_isPreprocessing(enum CXCursorKind K) {
2801 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2802}
2803
Ted Kremenekad6eff62010-03-08 21:17:29 +00002804unsigned clang_isUnexposed(enum CXCursorKind K) {
2805 switch (K) {
2806 case CXCursor_UnexposedDecl:
2807 case CXCursor_UnexposedExpr:
2808 case CXCursor_UnexposedStmt:
2809 case CXCursor_UnexposedAttr:
2810 return true;
2811 default:
2812 return false;
2813 }
2814}
2815
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002816CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002817 return C.kind;
2818}
2819
Douglas Gregor98258af2010-01-18 22:46:11 +00002820CXSourceLocation clang_getCursorLocation(CXCursor C) {
2821 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002822 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002823 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002824 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2825 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002826 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002827 }
2828
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002829 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002830 std::pair<ObjCProtocolDecl *, SourceLocation> P
2831 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002832 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002833 }
2834
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002835 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002836 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2837 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002838 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002839 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002840
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002841 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002842 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002843 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002844 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002845
2846 case CXCursor_TemplateRef: {
2847 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2848 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2849 }
2850
Douglas Gregor69319002010-08-31 23:48:11 +00002851 case CXCursor_NamespaceRef: {
2852 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2853 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2854 }
2855
Douglas Gregora67e03f2010-09-09 21:42:20 +00002856 case CXCursor_MemberRef: {
2857 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
2858 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2859 }
2860
Ted Kremenek3064ef92010-08-27 21:34:58 +00002861 case CXCursor_CXXBaseSpecifier: {
2862 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2863 return clang_getNullLocation();
2864 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002865
Douglas Gregorf46034a2010-01-18 23:41:10 +00002866 default:
2867 // FIXME: Need a way to enumerate all non-reference cases.
2868 llvm_unreachable("Missed a reference kind");
2869 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002870 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002871
2872 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002873 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002874 getLocationFromExpr(getCursorExpr(C)));
2875
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002876 if (C.kind == CXCursor_PreprocessingDirective) {
2877 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2878 return cxloc::translateSourceLocation(getCursorContext(C), L);
2879 }
Douglas Gregor48072312010-03-18 15:23:44 +00002880
2881 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002882 SourceLocation L
2883 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002884 return cxloc::translateSourceLocation(getCursorContext(C), L);
2885 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002886
2887 if (C.kind == CXCursor_MacroDefinition) {
2888 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2889 return cxloc::translateSourceLocation(getCursorContext(C), L);
2890 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002891
Ted Kremenek9a700d22010-05-12 06:16:13 +00002892 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002893 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002894
Douglas Gregorf46034a2010-01-18 23:41:10 +00002895 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002896 SourceLocation Loc = D->getLocation();
2897 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2898 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002899 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002900}
Douglas Gregora7bde202010-01-19 00:34:46 +00002901
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002902} // end extern "C"
2903
2904static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002905 if (clang_isReference(C.kind)) {
2906 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002907 case CXCursor_ObjCSuperClassRef:
2908 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002909
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002910 case CXCursor_ObjCProtocolRef:
2911 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002912
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002913 case CXCursor_ObjCClassRef:
2914 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002915
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002916 case CXCursor_TypeRef:
2917 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002918
2919 case CXCursor_TemplateRef:
2920 return getCursorTemplateRef(C).second;
2921
Douglas Gregor69319002010-08-31 23:48:11 +00002922 case CXCursor_NamespaceRef:
2923 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00002924
2925 case CXCursor_MemberRef:
2926 return getCursorMemberRef(C).second;
2927
Ted Kremenek3064ef92010-08-27 21:34:58 +00002928 case CXCursor_CXXBaseSpecifier:
2929 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2930 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002931
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002932 default:
2933 // FIXME: Need a way to enumerate all non-reference cases.
2934 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002935 }
2936 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002937
2938 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002939 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002940
2941 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002942 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002943
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002944 if (C.kind == CXCursor_PreprocessingDirective)
2945 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002946
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002947 if (C.kind == CXCursor_MacroInstantiation)
2948 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002949
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002950 if (C.kind == CXCursor_MacroDefinition)
2951 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002952
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002953 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2954 return getCursorDecl(C)->getSourceRange();
2955
2956 return SourceRange();
2957}
2958
2959extern "C" {
2960
2961CXSourceRange clang_getCursorExtent(CXCursor C) {
2962 SourceRange R = getRawCursorExtent(C);
2963 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002964 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002965
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002966 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002967}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002968
2969CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002970 if (clang_isInvalid(C.kind))
2971 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002972
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002973 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002974 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002975 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002976
Douglas Gregor97b98722010-01-19 23:20:36 +00002977 if (clang_isExpression(C.kind)) {
2978 Decl *D = getDeclFromExpr(getCursorExpr(C));
2979 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002980 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002981 return clang_getNullCursor();
2982 }
2983
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002984 if (C.kind == CXCursor_MacroInstantiation) {
2985 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2986 return MakeMacroDefinitionCursor(Def, CXXUnit);
2987 }
2988
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002989 if (!clang_isReference(C.kind))
2990 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002991
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002992 switch (C.kind) {
2993 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002994 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002995
2996 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002997 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002998
2999 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003000 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003001
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003002 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003003 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003004
3005 case CXCursor_TemplateRef:
3006 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3007
Douglas Gregor69319002010-08-31 23:48:11 +00003008 case CXCursor_NamespaceRef:
3009 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3010
Douglas Gregora67e03f2010-09-09 21:42:20 +00003011 case CXCursor_MemberRef:
3012 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3013
Ted Kremenek3064ef92010-08-27 21:34:58 +00003014 case CXCursor_CXXBaseSpecifier: {
3015 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3016 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3017 CXXUnit));
3018 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003019
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003020 default:
3021 // We would prefer to enumerate all non-reference cursor kinds here.
3022 llvm_unreachable("Unhandled reference cursor kind");
3023 break;
3024 }
3025 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003026
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003027 return clang_getNullCursor();
3028}
3029
Douglas Gregorb6998662010-01-19 19:34:47 +00003030CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003031 if (clang_isInvalid(C.kind))
3032 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003033
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003034 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003035
Douglas Gregorb6998662010-01-19 19:34:47 +00003036 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003037 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003038 C = clang_getCursorReferenced(C);
3039 WasReference = true;
3040 }
3041
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003042 if (C.kind == CXCursor_MacroInstantiation)
3043 return clang_getCursorReferenced(C);
3044
Douglas Gregorb6998662010-01-19 19:34:47 +00003045 if (!clang_isDeclaration(C.kind))
3046 return clang_getNullCursor();
3047
3048 Decl *D = getCursorDecl(C);
3049 if (!D)
3050 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003051
Douglas Gregorb6998662010-01-19 19:34:47 +00003052 switch (D->getKind()) {
3053 // Declaration kinds that don't really separate the notions of
3054 // declaration and definition.
3055 case Decl::Namespace:
3056 case Decl::Typedef:
3057 case Decl::TemplateTypeParm:
3058 case Decl::EnumConstant:
3059 case Decl::Field:
3060 case Decl::ObjCIvar:
3061 case Decl::ObjCAtDefsField:
3062 case Decl::ImplicitParam:
3063 case Decl::ParmVar:
3064 case Decl::NonTypeTemplateParm:
3065 case Decl::TemplateTemplateParm:
3066 case Decl::ObjCCategoryImpl:
3067 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003068 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003069 case Decl::LinkageSpec:
3070 case Decl::ObjCPropertyImpl:
3071 case Decl::FileScopeAsm:
3072 case Decl::StaticAssert:
3073 case Decl::Block:
3074 return C;
3075
3076 // Declaration kinds that don't make any sense here, but are
3077 // nonetheless harmless.
3078 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003079 break;
3080
3081 // Declaration kinds for which the definition is not resolvable.
3082 case Decl::UnresolvedUsingTypename:
3083 case Decl::UnresolvedUsingValue:
3084 break;
3085
3086 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003087 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3088 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003089
3090 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003091 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003092
3093 case Decl::Enum:
3094 case Decl::Record:
3095 case Decl::CXXRecord:
3096 case Decl::ClassTemplateSpecialization:
3097 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003098 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003099 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003100 return clang_getNullCursor();
3101
3102 case Decl::Function:
3103 case Decl::CXXMethod:
3104 case Decl::CXXConstructor:
3105 case Decl::CXXDestructor:
3106 case Decl::CXXConversion: {
3107 const FunctionDecl *Def = 0;
3108 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003109 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003110 return clang_getNullCursor();
3111 }
3112
3113 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003114 // Ask the variable if it has a definition.
3115 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3116 return MakeCXCursor(Def, CXXUnit);
3117 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003118 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003119
Douglas Gregorb6998662010-01-19 19:34:47 +00003120 case Decl::FunctionTemplate: {
3121 const FunctionDecl *Def = 0;
3122 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003123 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003124 return clang_getNullCursor();
3125 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003126
Douglas Gregorb6998662010-01-19 19:34:47 +00003127 case Decl::ClassTemplate: {
3128 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003129 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003130 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003131 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003132 return clang_getNullCursor();
3133 }
3134
3135 case Decl::Using: {
3136 UsingDecl *Using = cast<UsingDecl>(D);
3137 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003138 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
3139 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00003140 S != SEnd; ++S) {
3141 if (Def != clang_getNullCursor()) {
3142 // FIXME: We have no way to return multiple results.
3143 return clang_getNullCursor();
3144 }
3145
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003146 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003147 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003148 }
3149
3150 return Def;
3151 }
3152
3153 case Decl::UsingShadow:
3154 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003155 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003156 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003157
3158 case Decl::ObjCMethod: {
3159 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3160 if (Method->isThisDeclarationADefinition())
3161 return C;
3162
3163 // Dig out the method definition in the associated
3164 // @implementation, if we have it.
3165 // FIXME: The ASTs should make finding the definition easier.
3166 if (ObjCInterfaceDecl *Class
3167 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3168 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3169 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3170 Method->isInstanceMethod()))
3171 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003172 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003173
3174 return clang_getNullCursor();
3175 }
3176
3177 case Decl::ObjCCategory:
3178 if (ObjCCategoryImplDecl *Impl
3179 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003180 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003181 return clang_getNullCursor();
3182
3183 case Decl::ObjCProtocol:
3184 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3185 return C;
3186 return clang_getNullCursor();
3187
3188 case Decl::ObjCInterface:
3189 // There are two notions of a "definition" for an Objective-C
3190 // class: the interface and its implementation. When we resolved a
3191 // reference to an Objective-C class, produce the @interface as
3192 // the definition; when we were provided with the interface,
3193 // produce the @implementation as the definition.
3194 if (WasReference) {
3195 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3196 return C;
3197 } else if (ObjCImplementationDecl *Impl
3198 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003199 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003200 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003201
Douglas Gregorb6998662010-01-19 19:34:47 +00003202 case Decl::ObjCProperty:
3203 // FIXME: We don't really know where to find the
3204 // ObjCPropertyImplDecls that implement this property.
3205 return clang_getNullCursor();
3206
3207 case Decl::ObjCCompatibleAlias:
3208 if (ObjCInterfaceDecl *Class
3209 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3210 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003211 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003212
Douglas Gregorb6998662010-01-19 19:34:47 +00003213 return clang_getNullCursor();
3214
3215 case Decl::ObjCForwardProtocol: {
3216 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
3217 if (Forward->protocol_size() == 1)
3218 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003219 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003220 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003221
3222 // FIXME: Cannot return multiple definitions.
3223 return clang_getNullCursor();
3224 }
3225
3226 case Decl::ObjCClass: {
3227 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
3228 if (Class->size() == 1) {
3229 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
3230 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003231 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003232 return clang_getNullCursor();
3233 }
3234
3235 // FIXME: Cannot return multiple definitions.
3236 return clang_getNullCursor();
3237 }
3238
3239 case Decl::Friend:
3240 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003241 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003242 return clang_getNullCursor();
3243
3244 case Decl::FriendTemplate:
3245 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003246 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003247 return clang_getNullCursor();
3248 }
3249
3250 return clang_getNullCursor();
3251}
3252
3253unsigned clang_isCursorDefinition(CXCursor C) {
3254 if (!clang_isDeclaration(C.kind))
3255 return 0;
3256
3257 return clang_getCursorDefinition(C) == C;
3258}
3259
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003260void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003261 const char **startBuf,
3262 const char **endBuf,
3263 unsigned *startLine,
3264 unsigned *startColumn,
3265 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003266 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003267 assert(getCursorDecl(C) && "CXCursor has null decl");
3268 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003269 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3270 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003271
Steve Naroff4ade6d62009-09-23 17:52:52 +00003272 SourceManager &SM = FD->getASTContext().getSourceManager();
3273 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3274 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3275 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3276 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3277 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3278 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3279}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003280
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003281void clang_enableStackTraces(void) {
3282 llvm::sys::PrintStackTraceOnErrorSignal();
3283}
3284
Ted Kremenekfb480492010-01-13 21:46:36 +00003285} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003286
Ted Kremenekfb480492010-01-13 21:46:36 +00003287//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003288// Token-based Operations.
3289//===----------------------------------------------------------------------===//
3290
3291/* CXToken layout:
3292 * int_data[0]: a CXTokenKind
3293 * int_data[1]: starting token location
3294 * int_data[2]: token length
3295 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003296 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003297 * otherwise unused.
3298 */
3299extern "C" {
3300
3301CXTokenKind clang_getTokenKind(CXToken CXTok) {
3302 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3303}
3304
3305CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3306 switch (clang_getTokenKind(CXTok)) {
3307 case CXToken_Identifier:
3308 case CXToken_Keyword:
3309 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003310 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3311 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003312
3313 case CXToken_Literal: {
3314 // We have stashed the starting pointer in the ptr_data field. Use it.
3315 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003316 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003317 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003318
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003319 case CXToken_Punctuation:
3320 case CXToken_Comment:
3321 break;
3322 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003323
3324 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003325 // deconstructing the source location.
3326 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3327 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003328 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003329
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003330 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3331 std::pair<FileID, unsigned> LocInfo
3332 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003333 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003334 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003335 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3336 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003337 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003338
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003339 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003340}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003341
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003342CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3343 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3344 if (!CXXUnit)
3345 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003346
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003347 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3348 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3349}
3350
3351CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3352 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003353 if (!CXXUnit)
3354 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003355
3356 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003357 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3358}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003359
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003360void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3361 CXToken **Tokens, unsigned *NumTokens) {
3362 if (Tokens)
3363 *Tokens = 0;
3364 if (NumTokens)
3365 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003366
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003367 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3368 if (!CXXUnit || !Tokens || !NumTokens)
3369 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003370
Douglas Gregorbdf60622010-03-05 21:16:25 +00003371 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3372
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003373 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003374 if (R.isInvalid())
3375 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003376
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003377 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3378 std::pair<FileID, unsigned> BeginLocInfo
3379 = SourceMgr.getDecomposedLoc(R.getBegin());
3380 std::pair<FileID, unsigned> EndLocInfo
3381 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003382
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003383 // Cannot tokenize across files.
3384 if (BeginLocInfo.first != EndLocInfo.first)
3385 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003386
3387 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003388 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003389 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003390 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003391 if (Invalid)
3392 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003393
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003394 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3395 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003396 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003397 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003398
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003399 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003400 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003401 llvm::SmallVector<CXToken, 32> CXTokens;
3402 Token Tok;
3403 do {
3404 // Lex the next token
3405 Lex.LexFromRawLexer(Tok);
3406 if (Tok.is(tok::eof))
3407 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003408
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003409 // Initialize the CXToken.
3410 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003411
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003412 // - Common fields
3413 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3414 CXTok.int_data[2] = Tok.getLength();
3415 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003416
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003417 // - Kind-specific fields
3418 if (Tok.isLiteral()) {
3419 CXTok.int_data[0] = CXToken_Literal;
3420 CXTok.ptr_data = (void *)Tok.getLiteralData();
3421 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003422 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003423 std::pair<FileID, unsigned> LocInfo
3424 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003425 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003426 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003427 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3428 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003429 return;
3430
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003431 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003432 IdentifierInfo *II
3433 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003434
3435 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3436 CXTok.int_data[0] = CXToken_Keyword;
3437 }
3438 else {
3439 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3440 CXToken_Identifier
3441 : CXToken_Keyword;
3442 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003443 CXTok.ptr_data = II;
3444 } else if (Tok.is(tok::comment)) {
3445 CXTok.int_data[0] = CXToken_Comment;
3446 CXTok.ptr_data = 0;
3447 } else {
3448 CXTok.int_data[0] = CXToken_Punctuation;
3449 CXTok.ptr_data = 0;
3450 }
3451 CXTokens.push_back(CXTok);
3452 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003453
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003454 if (CXTokens.empty())
3455 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003456
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003457 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3458 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3459 *NumTokens = CXTokens.size();
3460}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003461
Ted Kremenek6db61092010-05-05 00:55:15 +00003462void clang_disposeTokens(CXTranslationUnit TU,
3463 CXToken *Tokens, unsigned NumTokens) {
3464 free(Tokens);
3465}
3466
3467} // end: extern "C"
3468
3469//===----------------------------------------------------------------------===//
3470// Token annotation APIs.
3471//===----------------------------------------------------------------------===//
3472
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003473typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003474static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3475 CXCursor parent,
3476 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003477namespace {
3478class AnnotateTokensWorker {
3479 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003480 CXToken *Tokens;
3481 CXCursor *Cursors;
3482 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003483 unsigned TokIdx;
3484 CursorVisitor AnnotateVis;
3485 SourceManager &SrcMgr;
3486
3487 bool MoreTokens() const { return TokIdx < NumTokens; }
3488 unsigned NextToken() const { return TokIdx; }
3489 void AdvanceToken() { ++TokIdx; }
3490 SourceLocation GetTokenLoc(unsigned tokI) {
3491 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3492 }
3493
Ted Kremenek6db61092010-05-05 00:55:15 +00003494public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003495 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003496 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3497 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003498 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003499 NumTokens(numTokens), TokIdx(0),
3500 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3501 Decl::MaxPCHLevel, RegionOfInterest),
3502 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003503
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003504 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003505 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003506 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003507};
3508}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003509
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003510void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3511 // Walk the AST within the region of interest, annotating tokens
3512 // along the way.
3513 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003514
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003515 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3516 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3517 if (Pos != Annotated.end())
3518 Cursors[I] = Pos->second;
3519 }
3520
3521 // Finish up annotating any tokens left.
3522 if (!MoreTokens())
3523 return;
3524
3525 const CXCursor &C = clang_getNullCursor();
3526 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3527 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3528 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003529 }
3530}
3531
Ted Kremenek6db61092010-05-05 00:55:15 +00003532enum CXChildVisitResult
3533AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003534 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3535 // We can always annotate a preprocessing directive/macro instantiation.
3536 if (clang_isPreprocessing(cursor.kind)) {
3537 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003538 return CXChildVisit_Recurse;
3539 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003540
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003541 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003542
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003543 if (cursorRange.isInvalid())
3544 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003545
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003546 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3547
Ted Kremeneka333c662010-05-12 05:29:33 +00003548 // Adjust the annotated range based specific declarations.
3549 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3550 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003551 Decl *D = cxcursor::getCursorDecl(cursor);
3552 // Don't visit synthesized ObjC methods, since they have no syntatic
3553 // representation in the source.
3554 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3555 if (MD->isSynthesized())
3556 return CXChildVisit_Continue;
3557 }
3558 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003559 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3560 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003561 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003562 if (TLoc.isValid() &&
3563 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003564 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003565 }
3566 }
3567 }
3568
Ted Kremenek3f404602010-08-14 01:14:06 +00003569 // If the location of the cursor occurs within a macro instantiation, record
3570 // the spelling location of the cursor in our annotation map. We can then
3571 // paper over the token labelings during a post-processing step to try and
3572 // get cursor mappings for tokens that are the *arguments* of a macro
3573 // instantiation.
3574 if (L.isMacroID()) {
3575 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3576 // Only invalidate the old annotation if it isn't part of a preprocessing
3577 // directive. Here we assume that the default construction of CXCursor
3578 // results in CXCursor.kind being an initialized value (i.e., 0). If
3579 // this isn't the case, we can fix by doing lookup + insertion.
3580
3581 CXCursor &oldC = Annotated[rawEncoding];
3582 if (!clang_isPreprocessing(oldC.kind))
3583 oldC = cursor;
3584 }
3585
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003586 const enum CXCursorKind K = clang_getCursorKind(parent);
3587 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003588 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3589 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003590
3591 while (MoreTokens()) {
3592 const unsigned I = NextToken();
3593 SourceLocation TokLoc = GetTokenLoc(I);
3594 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3595 case RangeBefore:
3596 Cursors[I] = updateC;
3597 AdvanceToken();
3598 continue;
3599 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003600 case RangeOverlap:
3601 break;
3602 }
3603 break;
3604 }
3605
3606 // Visit children to get their cursor information.
3607 const unsigned BeforeChildren = NextToken();
3608 VisitChildren(cursor);
3609 const unsigned AfterChildren = NextToken();
3610
3611 // Adjust 'Last' to the last token within the extent of the cursor.
3612 while (MoreTokens()) {
3613 const unsigned I = NextToken();
3614 SourceLocation TokLoc = GetTokenLoc(I);
3615 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3616 case RangeBefore:
3617 assert(0 && "Infeasible");
3618 case RangeAfter:
3619 break;
3620 case RangeOverlap:
3621 Cursors[I] = updateC;
3622 AdvanceToken();
3623 continue;
3624 }
3625 break;
3626 }
3627 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003628
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003629 // Scan the tokens that are at the beginning of the cursor, but are not
3630 // capture by the child cursors.
3631
3632 // For AST elements within macros, rely on a post-annotate pass to
3633 // to correctly annotate the tokens with cursors. Otherwise we can
3634 // get confusing results of having tokens that map to cursors that really
3635 // are expanded by an instantiation.
3636 if (L.isMacroID())
3637 cursor = clang_getNullCursor();
3638
3639 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3640 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3641 break;
3642 Cursors[I] = cursor;
3643 }
3644 // Scan the tokens that are at the end of the cursor, but are not captured
3645 // but the child cursors.
3646 for (unsigned I = AfterChildren; I != Last; ++I)
3647 Cursors[I] = cursor;
3648
3649 TokIdx = Last;
3650 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003651}
3652
Ted Kremenek6db61092010-05-05 00:55:15 +00003653static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3654 CXCursor parent,
3655 CXClientData client_data) {
3656 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3657}
3658
3659extern "C" {
3660
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003661void clang_annotateTokens(CXTranslationUnit TU,
3662 CXToken *Tokens, unsigned NumTokens,
3663 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003664
3665 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003666 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003667
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003668 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003669 if (!CXXUnit) {
3670 // Any token we don't specifically annotate will have a NULL cursor.
3671 const CXCursor &C = clang_getNullCursor();
3672 for (unsigned I = 0; I != NumTokens; ++I)
3673 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003674 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003675 }
3676
Douglas Gregorbdf60622010-03-05 21:16:25 +00003677 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003678
Douglas Gregor0396f462010-03-19 05:22:59 +00003679 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003680 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003681 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3682 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003683 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3684 clang_getTokenLocation(TU,
3685 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003686
Douglas Gregor0396f462010-03-19 05:22:59 +00003687 // A mapping from the source locations found when re-lexing or traversing the
3688 // region of interest to the corresponding cursors.
3689 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003690
3691 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003692 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003693 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3694 std::pair<FileID, unsigned> BeginLocInfo
3695 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3696 std::pair<FileID, unsigned> EndLocInfo
3697 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003698
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003699 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003700 bool Invalid = false;
3701 if (BeginLocInfo.first == EndLocInfo.first &&
3702 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3703 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003704 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3705 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003706 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003707 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003708 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003709
3710 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003711 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003712 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003713 Token Tok;
3714 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003715
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003716 reprocess:
3717 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3718 // We have found a preprocessing directive. Gobble it up so that we
3719 // don't see it while preprocessing these tokens later, but keep track of
3720 // all of the token locations inside this preprocessing directive so that
3721 // we can annotate them appropriately.
3722 //
3723 // FIXME: Some simple tests here could identify macro definitions and
3724 // #undefs, to provide specific cursor kinds for those.
3725 std::vector<SourceLocation> Locations;
3726 do {
3727 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003728 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003729 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003730
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003731 using namespace cxcursor;
3732 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003733 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3734 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003735 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003736 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3737 Annotated[Locations[I].getRawEncoding()] = Cursor;
3738 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003739
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003740 if (Tok.isAtStartOfLine())
3741 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003742
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003743 continue;
3744 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003745
Douglas Gregor48072312010-03-18 15:23:44 +00003746 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003747 break;
3748 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003749 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003750
Douglas Gregor0396f462010-03-19 05:22:59 +00003751 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003752 // a specific cursor.
3753 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3754 CXXUnit, RegionOfInterest);
3755 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003756}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003757} // end: extern "C"
3758
3759//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003760// Operations for querying linkage of a cursor.
3761//===----------------------------------------------------------------------===//
3762
3763extern "C" {
3764CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003765 if (!clang_isDeclaration(cursor.kind))
3766 return CXLinkage_Invalid;
3767
Ted Kremenek16b42592010-03-03 06:36:57 +00003768 Decl *D = cxcursor::getCursorDecl(cursor);
3769 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3770 switch (ND->getLinkage()) {
3771 case NoLinkage: return CXLinkage_NoLinkage;
3772 case InternalLinkage: return CXLinkage_Internal;
3773 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3774 case ExternalLinkage: return CXLinkage_External;
3775 };
3776
3777 return CXLinkage_Invalid;
3778}
3779} // end: extern "C"
3780
3781//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003782// Operations for querying language of a cursor.
3783//===----------------------------------------------------------------------===//
3784
3785static CXLanguageKind getDeclLanguage(const Decl *D) {
3786 switch (D->getKind()) {
3787 default:
3788 break;
3789 case Decl::ImplicitParam:
3790 case Decl::ObjCAtDefsField:
3791 case Decl::ObjCCategory:
3792 case Decl::ObjCCategoryImpl:
3793 case Decl::ObjCClass:
3794 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003795 case Decl::ObjCForwardProtocol:
3796 case Decl::ObjCImplementation:
3797 case Decl::ObjCInterface:
3798 case Decl::ObjCIvar:
3799 case Decl::ObjCMethod:
3800 case Decl::ObjCProperty:
3801 case Decl::ObjCPropertyImpl:
3802 case Decl::ObjCProtocol:
3803 return CXLanguage_ObjC;
3804 case Decl::CXXConstructor:
3805 case Decl::CXXConversion:
3806 case Decl::CXXDestructor:
3807 case Decl::CXXMethod:
3808 case Decl::CXXRecord:
3809 case Decl::ClassTemplate:
3810 case Decl::ClassTemplatePartialSpecialization:
3811 case Decl::ClassTemplateSpecialization:
3812 case Decl::Friend:
3813 case Decl::FriendTemplate:
3814 case Decl::FunctionTemplate:
3815 case Decl::LinkageSpec:
3816 case Decl::Namespace:
3817 case Decl::NamespaceAlias:
3818 case Decl::NonTypeTemplateParm:
3819 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003820 case Decl::TemplateTemplateParm:
3821 case Decl::TemplateTypeParm:
3822 case Decl::UnresolvedUsingTypename:
3823 case Decl::UnresolvedUsingValue:
3824 case Decl::Using:
3825 case Decl::UsingDirective:
3826 case Decl::UsingShadow:
3827 return CXLanguage_CPlusPlus;
3828 }
3829
3830 return CXLanguage_C;
3831}
3832
3833extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003834
3835enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3836 if (clang_isDeclaration(cursor.kind))
3837 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3838 if (D->hasAttr<UnavailableAttr>() ||
3839 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3840 return CXAvailability_Available;
3841
3842 if (D->hasAttr<DeprecatedAttr>())
3843 return CXAvailability_Deprecated;
3844 }
3845
3846 return CXAvailability_Available;
3847}
3848
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003849CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3850 if (clang_isDeclaration(cursor.kind))
3851 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3852
3853 return CXLanguage_Invalid;
3854}
3855} // end: extern "C"
3856
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003857
3858//===----------------------------------------------------------------------===//
3859// C++ AST instrospection.
3860//===----------------------------------------------------------------------===//
3861
3862extern "C" {
3863unsigned clang_CXXMethod_isStatic(CXCursor C) {
3864 if (!clang_isDeclaration(C.kind))
3865 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003866
3867 CXXMethodDecl *Method = 0;
3868 Decl *D = cxcursor::getCursorDecl(C);
3869 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3870 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3871 else
3872 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3873 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003874}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003875
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003876} // end: extern "C"
3877
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003878//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003879// Attribute introspection.
3880//===----------------------------------------------------------------------===//
3881
3882extern "C" {
3883CXType clang_getIBOutletCollectionType(CXCursor C) {
3884 if (C.kind != CXCursor_IBOutletCollectionAttr)
3885 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3886
3887 IBOutletCollectionAttr *A =
3888 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3889
3890 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3891}
3892} // end: extern "C"
3893
3894//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003895// CXString Operations.
3896//===----------------------------------------------------------------------===//
3897
3898extern "C" {
3899const char *clang_getCString(CXString string) {
3900 return string.Spelling;
3901}
3902
3903void clang_disposeString(CXString string) {
3904 if (string.MustFreeString && string.Spelling)
3905 free((void*)string.Spelling);
3906}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003907
Ted Kremenekfb480492010-01-13 21:46:36 +00003908} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003909
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003910namespace clang { namespace cxstring {
3911CXString createCXString(const char *String, bool DupString){
3912 CXString Str;
3913 if (DupString) {
3914 Str.Spelling = strdup(String);
3915 Str.MustFreeString = 1;
3916 } else {
3917 Str.Spelling = String;
3918 Str.MustFreeString = 0;
3919 }
3920 return Str;
3921}
3922
3923CXString createCXString(llvm::StringRef String, bool DupString) {
3924 CXString Result;
3925 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3926 char *Spelling = (char *)malloc(String.size() + 1);
3927 memmove(Spelling, String.data(), String.size());
3928 Spelling[String.size()] = 0;
3929 Result.Spelling = Spelling;
3930 Result.MustFreeString = 1;
3931 } else {
3932 Result.Spelling = String.data();
3933 Result.MustFreeString = 0;
3934 }
3935 return Result;
3936}
3937}}
3938
Ted Kremenek04bb7162010-01-22 22:44:15 +00003939//===----------------------------------------------------------------------===//
3940// Misc. utility functions.
3941//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003942
Ted Kremenek04bb7162010-01-22 22:44:15 +00003943extern "C" {
3944
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003945CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003946 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003947}
3948
3949} // end: extern "C"