blob: 6367de34a38c5123dc09ae4bb166dce3c123078a [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"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000033#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor02465752009-10-16 21:24:31 +000034#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000035#include "llvm/Support/Timer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000036#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000037#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000038
Benjamin Kramerc2a98162010-03-13 21:22:49 +000039// Needed to define L_TMPNAM on some systems.
40#include <cstdio>
41
Steve Naroff50398192009-08-28 15:28:48 +000042using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000043using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000044using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000045
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000046//===----------------------------------------------------------------------===//
47// Crash Reporting.
48//===----------------------------------------------------------------------===//
49
Ted Kremenekd7ffd082010-05-22 00:06:46 +000050#ifdef USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000051#include "clang/Analysis/Support/SaveAndRestore.h"
52// Integrate with crash reporter.
Daniel Dunbar439794e2010-05-20 23:50:23 +000053static const char *__crashreporter_info__ = 0;
54asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek6b569992010-02-17 21:12:23 +000055#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000056static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000057static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000058static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
59static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
60
61static unsigned SetCrashTracerInfo(const char *str,
62 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000063
Ted Kremenek254ba7c2010-01-07 23:13:53 +000064 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000065 while (crashtracer_strings[slot]) {
66 if (++slot == NUM_CRASH_STRINGS)
67 slot = 0;
68 }
69 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000070 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000071
72 // We need to create an aggregate string because multiple threads
73 // may be in this method at one time. The crash reporter string
74 // will attempt to overapproximate the set of in-flight invocations
75 // of this function. Race conditions can still cause this goal
76 // to not be achieved.
77 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000078 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000079 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
80 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
81 }
82 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
83 return slot;
84}
85
86static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000087 unsigned max_slot = 0;
88 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000089
Ted Kremenek254ba7c2010-01-07 23:13:53 +000090 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
91
92 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
93 if (agg_crashtracer_strings[i] &&
94 crashtracer_counter_id[i] > max_value) {
95 max_slot = i;
96 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000097 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000098
99 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +0000100}
101
102namespace {
103class ArgsCrashTracerInfo {
104 llvm::SmallString<1024> CrashString;
105 llvm::SmallString<1024> AggregateString;
106 unsigned crashtracerSlot;
107public:
108 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
109 : crashtracerSlot(0)
110 {
111 {
112 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000113 Out << "ClangCIndex [" << getClangFullVersion() << "]"
114 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000115 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
116 E=Args.end(); I!=E; ++I)
117 Out << ' ' << *I;
118 }
119 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
120 AggregateString);
121 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000122
Ted Kremenek29b72842010-01-07 22:49:05 +0000123 ~ArgsCrashTracerInfo() {
124 ResetCrashTracerInfo(crashtracerSlot);
125 }
126};
127}
128#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000129
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000130/// \brief The result of comparing two source ranges.
131enum RangeComparisonResult {
132 /// \brief Either the ranges overlap or one of the ranges is invalid.
133 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135 /// \brief The first range ends before the second range starts.
136 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000137
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000138 /// \brief The first range starts after the second range ends.
139 RangeAfter
140};
141
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000142/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000143/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000144static RangeComparisonResult RangeCompare(SourceManager &SM,
145 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000146 SourceRange R2) {
147 assert(R1.isValid() && "First range is invalid?");
148 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000149 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000150 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000152 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +0000153 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000154 return RangeAfter;
155 return RangeOverlap;
156}
157
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000158/// \brief Determine if a source location falls within, before, or after a
159/// a given source range.
160static RangeComparisonResult LocationCompare(SourceManager &SM,
161 SourceLocation L, SourceRange R) {
162 assert(R.isValid() && "First range is invalid?");
163 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000164 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000165 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +0000166 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
167 return RangeBefore;
168 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
169 return RangeAfter;
170 return RangeOverlap;
171}
172
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000173/// \brief Translate a Clang source range into a CIndex source range.
174///
175/// Clang internally represents ranges where the end location points to the
176/// start of the token at the end. However, for external clients it is more
177/// useful to have a CXSourceRange be a proper half-open interval. This routine
178/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000179CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000180 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000181 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000182 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000183 // location accordingly.
184 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000185 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000186 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000187 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000188 EndLoc = EndLoc.getFileLocWithOffset(Length);
189 }
190
191 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
192 R.getBegin().getRawEncoding(),
193 EndLoc.getRawEncoding() };
194 return Result;
195}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000196
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000197//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000198// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000199//===----------------------------------------------------------------------===//
200
Steve Naroff89922f82009-08-31 00:59:03 +0000201namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000202
Douglas Gregorb1373d02010-01-20 20:59:29 +0000203// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000204class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000205 public TypeLocVisitor<CursorVisitor, bool>,
206 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000207{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000209 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000211 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000212 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000213
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000214 /// \brief The declaration that serves at the parent of any statement or
215 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000216 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000217
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000219 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000221 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000222 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000223
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000224 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
225 // to the visitor. Declarations with a PCH level greater than this value will
226 // be suppressed.
227 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000228
229 /// \brief When valid, a source range to which the cursor should restrict
230 /// its search.
231 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000232
Douglas Gregorb1373d02010-01-20 20:59:29 +0000233 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000234 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000235 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000236
237 /// \brief Determine whether this particular source range comes before, comes
238 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000239 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000240 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000241 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
242
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000243 class SetParentRAII {
244 CXCursor &Parent;
245 Decl *&StmtParent;
246 CXCursor OldParent;
247
248 public:
249 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
250 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
251 {
252 Parent = NewParent;
253 if (clang_isDeclaration(Parent.kind))
254 StmtParent = getCursorDecl(Parent);
255 }
256
257 ~SetParentRAII() {
258 Parent = OldParent;
259 if (clang_isDeclaration(Parent.kind))
260 StmtParent = getCursorDecl(Parent);
261 }
262 };
263
Steve Naroff89922f82009-08-31 00:59:03 +0000264public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000265 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
266 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000267 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000268 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000269 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000270 {
271 Parent.kind = CXCursor_NoDeclFound;
272 Parent.data[0] = 0;
273 Parent.data[1] = 0;
274 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000275 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000276 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000277
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000278 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000279
280 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
281 getPreprocessedEntities();
282
Douglas Gregorb1373d02010-01-20 20:59:29 +0000283 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000284
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000285 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000286 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000287 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000288 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000289 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000290 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
291 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000292 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000293 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000294 bool VisitClassTemplatePartialSpecializationDecl(
295 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000296 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000297 bool VisitEnumConstantDecl(EnumConstantDecl *D);
298 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
299 bool VisitFunctionDecl(FunctionDecl *ND);
300 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000301 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000302 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000303 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000304 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000305 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000306 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
307 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
308 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
309 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000310 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000311 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
312 bool VisitObjCImplDecl(ObjCImplDecl *D);
313 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
314 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
315 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
316 // etc.
317 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
318 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
319 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000320 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000321 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000322 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000323 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000324 bool VisitUsingDecl(UsingDecl *D);
325 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
326 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000327
Douglas Gregor01829d32010-08-31 14:41:23 +0000328 // Name visitor
329 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000330 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000331
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000332 // Template visitors
333 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000334 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000335 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
336
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000337 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000338 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000339 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000340 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000341 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
342 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000343 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000344 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000345 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000346 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
347 bool VisitPointerTypeLoc(PointerTypeLoc TL);
348 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
349 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
350 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
351 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000352 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000353 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000354 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000355 // FIXME: Implement visitors here when the unimplemented TypeLocs get
356 // implemented
357 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
358 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000359
Douglas Gregora59e3902010-01-21 23:27:09 +0000360 // Statement visitors
361 bool VisitStmt(Stmt *S);
362 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000363 // FIXME: LabelStmt label?
364 bool VisitIfStmt(IfStmt *S);
365 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000366 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000367 bool VisitWhileStmt(WhileStmt *S);
368 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000369// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000370
Douglas Gregor336fd812010-01-23 00:40:08 +0000371 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000372 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000373 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000374 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000375 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000376 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000377 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000378 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000379 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000380 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000381 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000382 // FIXME: AddrLabelExpr (once we have cursors for labels)
383 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
384 bool VisitVAArgExpr(VAArgExpr *E);
385 // FIXME: InitListExpr (for the designators)
386 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000387};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000388
Ted Kremenekab188932010-01-05 19:32:54 +0000389} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000390
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000391static SourceRange getRawCursorExtent(CXCursor C);
392
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000393RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000394 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
395}
396
Douglas Gregorb1373d02010-01-20 20:59:29 +0000397/// \brief Visit the given cursor and, if requested by the visitor,
398/// its children.
399///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000400/// \param Cursor the cursor to visit.
401///
402/// \param CheckRegionOfInterest if true, then the caller already checked that
403/// this cursor is within the region of interest.
404///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405/// \returns true if the visitation should be aborted, false if it
406/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000407bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408 if (clang_isInvalid(Cursor.kind))
409 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000410
Douglas Gregorb1373d02010-01-20 20:59:29 +0000411 if (clang_isDeclaration(Cursor.kind)) {
412 Decl *D = getCursorDecl(Cursor);
413 assert(D && "Invalid declaration cursor");
414 if (D->getPCHLevel() > MaxPCHLevel)
415 return false;
416
417 if (D->isImplicit())
418 return false;
419 }
420
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000421 // If we have a range of interest, and this cursor doesn't intersect with it,
422 // we're done.
423 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000424 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000425 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000426 return false;
427 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000428
Douglas Gregorb1373d02010-01-20 20:59:29 +0000429 switch (Visitor(Cursor, Parent, ClientData)) {
430 case CXChildVisit_Break:
431 return true;
432
433 case CXChildVisit_Continue:
434 return false;
435
436 case CXChildVisit_Recurse:
437 return VisitChildren(Cursor);
438 }
439
Douglas Gregorfd643772010-01-25 16:45:46 +0000440 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000441}
442
Douglas Gregor788f5a12010-03-20 00:41:21 +0000443std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
444CursorVisitor::getPreprocessedEntities() {
445 PreprocessingRecord &PPRec
446 = *TU->getPreprocessor().getPreprocessingRecord();
447
448 bool OnlyLocalDecls
449 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
450
451 // There is no region of interest; we have to walk everything.
452 if (RegionOfInterest.isInvalid())
453 return std::make_pair(PPRec.begin(OnlyLocalDecls),
454 PPRec.end(OnlyLocalDecls));
455
456 // Find the file in which the region of interest lands.
457 SourceManager &SM = TU->getSourceManager();
458 std::pair<FileID, unsigned> Begin
459 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
460 std::pair<FileID, unsigned> End
461 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
462
463 // The region of interest spans files; we have to walk everything.
464 if (Begin.first != End.first)
465 return std::make_pair(PPRec.begin(OnlyLocalDecls),
466 PPRec.end(OnlyLocalDecls));
467
468 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
469 = TU->getPreprocessedEntitiesByFile();
470 if (ByFileMap.empty()) {
471 // Build the mapping from files to sets of preprocessed entities.
472 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
473 EEnd = PPRec.end(OnlyLocalDecls);
474 E != EEnd; ++E) {
475 std::pair<FileID, unsigned> P
476 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
477 ByFileMap[P.first].push_back(*E);
478 }
479 }
480
481 return std::make_pair(ByFileMap[Begin.first].begin(),
482 ByFileMap[Begin.first].end());
483}
484
Douglas Gregorb1373d02010-01-20 20:59:29 +0000485/// \brief Visit the children of the given cursor.
486///
487/// \returns true if the visitation should be aborted, false if it
488/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000489bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000490 if (clang_isReference(Cursor.kind)) {
491 // By definition, references have no children.
492 return false;
493 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000494
495 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000496 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000497 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000498
Douglas Gregorb1373d02010-01-20 20:59:29 +0000499 if (clang_isDeclaration(Cursor.kind)) {
500 Decl *D = getCursorDecl(Cursor);
501 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000502 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000503 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000504
Douglas Gregora59e3902010-01-21 23:27:09 +0000505 if (clang_isStatement(Cursor.kind))
506 return Visit(getCursorStmt(Cursor));
507 if (clang_isExpression(Cursor.kind))
508 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000509
Douglas Gregorb1373d02010-01-20 20:59:29 +0000510 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000511 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000512 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
513 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000514 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
515 TLEnd = CXXUnit->top_level_end();
516 TL != TLEnd; ++TL) {
517 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000518 return true;
519 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000520 } else if (VisitDeclContext(
521 CXXUnit->getASTContext().getTranslationUnitDecl()))
522 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000523
Douglas Gregor0396f462010-03-19 05:22:59 +0000524 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000525 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000526 // FIXME: Once we have the ability to deserialize a preprocessing record,
527 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000528 PreprocessingRecord::iterator E, EEnd;
529 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000530 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
531 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
532 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000533
Douglas Gregor0396f462010-03-19 05:22:59 +0000534 continue;
535 }
536
537 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
538 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
539 return true;
540
541 continue;
542 }
543 }
544 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000545 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000546 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000547
Douglas Gregorb1373d02010-01-20 20:59:29 +0000548 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000549 return false;
550}
551
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000552bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000553 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
554 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000555
Ted Kremenek664cffd2010-07-22 11:30:19 +0000556 if (Stmt *Body = B->getBody())
557 return Visit(MakeCXCursor(Body, StmtParent, TU));
558
559 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000560}
561
Douglas Gregorb1373d02010-01-20 20:59:29 +0000562bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000563 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000564 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000565
Ted Kremenek23173d72010-05-18 21:09:07 +0000566 Decl *D = *I;
567 if (D->getLexicalDeclContext() != DC)
568 continue;
569
570 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000571
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000572 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000573 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000574 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000575 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000576
577 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000578 case RangeBefore:
579 // This declaration comes before the region of interest; skip it.
580 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000581
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000582 case RangeAfter:
583 // This declaration comes after the region of interest; we're done.
584 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000585
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000586 case RangeOverlap:
587 // This declaration overlaps the region of interest; visit it.
588 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000589 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000590 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000591
Daniel Dunbard52864b2010-02-14 10:02:57 +0000592 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000593 return true;
594 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000595
Douglas Gregorb1373d02010-01-20 20:59:29 +0000596 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000597}
598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
600 llvm_unreachable("Translation units are visited directly by Visit()");
601 return false;
602}
603
604bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
605 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
606 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608 return false;
609}
610
611bool CursorVisitor::VisitTagDecl(TagDecl *D) {
612 return VisitDeclContext(D);
613}
614
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000615bool CursorVisitor::VisitClassTemplateSpecializationDecl(
616 ClassTemplateSpecializationDecl *D) {
617 bool ShouldVisitBody = false;
618 switch (D->getSpecializationKind()) {
619 case TSK_Undeclared:
620 case TSK_ImplicitInstantiation:
621 // Nothing to visit
622 return false;
623
624 case TSK_ExplicitInstantiationDeclaration:
625 case TSK_ExplicitInstantiationDefinition:
626 break;
627
628 case TSK_ExplicitSpecialization:
629 ShouldVisitBody = true;
630 break;
631 }
632
633 // Visit the template arguments used in the specialization.
634 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
635 TypeLoc TL = SpecType->getTypeLoc();
636 if (TemplateSpecializationTypeLoc *TSTLoc
637 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
638 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
639 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
640 return true;
641 }
642 }
643
644 if (ShouldVisitBody && VisitCXXRecordDecl(D))
645 return true;
646
647 return false;
648}
649
Douglas Gregor74dbe642010-08-31 19:31:58 +0000650bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
651 ClassTemplatePartialSpecializationDecl *D) {
652 // FIXME: Visit the "outer" template parameter lists on the TagDecl
653 // before visiting these template parameters.
654 if (VisitTemplateParameters(D->getTemplateParameters()))
655 return true;
656
657 // Visit the partial specialization arguments.
658 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
659 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
660 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
661 return true;
662
663 return VisitCXXRecordDecl(D);
664}
665
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000666bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000667 // Visit the default argument.
668 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
669 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
670 if (Visit(DefArg->getTypeLoc()))
671 return true;
672
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000673 return false;
674}
675
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000676bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
677 if (Expr *Init = D->getInitExpr())
678 return Visit(MakeCXCursor(Init, StmtParent, TU));
679 return false;
680}
681
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000682bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
683 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
684 if (Visit(TSInfo->getTypeLoc()))
685 return true;
686
687 return false;
688}
689
Douglas Gregorb1373d02010-01-20 20:59:29 +0000690bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000691 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
692 // Visit the function declaration's syntactic components in the order
693 // written. This requires a bit of work.
694 TypeLoc TL = TSInfo->getTypeLoc();
695 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
696
697 // If we have a function declared directly (without the use of a typedef),
698 // visit just the return type. Otherwise, just visit the function's type
699 // now.
700 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
701 (!FTL && Visit(TL)))
702 return true;
703
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000704 // Visit the nested-name-specifier, if present.
705 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
706 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
707 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000708
709 // Visit the declaration name.
710 if (VisitDeclarationNameInfo(ND->getNameInfo()))
711 return true;
712
713 // FIXME: Visit explicitly-specified template arguments!
714
715 // Visit the function parameters, if we have a function type.
716 if (FTL && VisitFunctionTypeLoc(*FTL, true))
717 return true;
718
719 // FIXME: Attributes?
720 }
721
Douglas Gregora59e3902010-01-21 23:27:09 +0000722 if (ND->isThisDeclarationADefinition() &&
723 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
724 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000725
Douglas Gregorb1373d02010-01-20 20:59:29 +0000726 return false;
727}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000728
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000729bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
730 if (VisitDeclaratorDecl(D))
731 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000732
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000733 if (Expr *BitWidth = D->getBitWidth())
734 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000735
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000736 return false;
737}
738
739bool CursorVisitor::VisitVarDecl(VarDecl *D) {
740 if (VisitDeclaratorDecl(D))
741 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000742
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000743 if (Expr *Init = D->getInit())
744 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000745
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000746 return false;
747}
748
Douglas Gregor84b51d72010-09-01 20:16:53 +0000749bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
750 if (VisitDeclaratorDecl(D))
751 return true;
752
753 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
754 if (Expr *DefArg = D->getDefaultArgument())
755 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
756
757 return false;
758}
759
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000760bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
761 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
762 // before visiting these template parameters.
763 if (VisitTemplateParameters(D->getTemplateParameters()))
764 return true;
765
766 return VisitFunctionDecl(D->getTemplatedDecl());
767}
768
Douglas Gregor39d6f072010-08-31 19:02:00 +0000769bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
770 // FIXME: Visit the "outer" template parameter lists on the TagDecl
771 // before visiting these template parameters.
772 if (VisitTemplateParameters(D->getTemplateParameters()))
773 return true;
774
775 return VisitCXXRecordDecl(D->getTemplatedDecl());
776}
777
Douglas Gregor84b51d72010-09-01 20:16:53 +0000778bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
779 if (VisitTemplateParameters(D->getTemplateParameters()))
780 return true;
781
782 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
783 VisitTemplateArgumentLoc(D->getDefaultArgument()))
784 return true;
785
786 return false;
787}
788
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000789bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000790 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
791 if (Visit(TSInfo->getTypeLoc()))
792 return true;
793
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000794 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795 PEnd = ND->param_end();
796 P != PEnd; ++P) {
797 if (Visit(MakeCXCursor(*P, TU)))
798 return true;
799 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000800
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000801 if (ND->isThisDeclarationADefinition() &&
802 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
803 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 return false;
806}
807
Douglas Gregora59e3902010-01-21 23:27:09 +0000808bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
809 return VisitDeclContext(D);
810}
811
Douglas Gregorb1373d02010-01-20 20:59:29 +0000812bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000813 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
814 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000815 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000816
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000817 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
818 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
819 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000820 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000821 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000822
Douglas Gregora59e3902010-01-21 23:27:09 +0000823 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000824}
825
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000826bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
827 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
828 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
829 E = PID->protocol_end(); I != E; ++I, ++PL)
830 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
831 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000832
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000833 return VisitObjCContainerDecl(PID);
834}
835
Ted Kremenek23173d72010-05-18 21:09:07 +0000836bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000837 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
838 return true;
839
Ted Kremenek23173d72010-05-18 21:09:07 +0000840 // FIXME: This implements a workaround with @property declarations also being
841 // installed in the DeclContext for the @interface. Eventually this code
842 // should be removed.
843 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
844 if (!CDecl || !CDecl->IsClassExtension())
845 return false;
846
847 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
848 if (!ID)
849 return false;
850
851 IdentifierInfo *PropertyId = PD->getIdentifier();
852 ObjCPropertyDecl *prevDecl =
853 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
854
855 if (!prevDecl)
856 return false;
857
858 // Visit synthesized methods since they will be skipped when visiting
859 // the @interface.
860 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
861 if (MD->isSynthesized())
862 if (Visit(MakeCXCursor(MD, TU)))
863 return true;
864
865 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
866 if (MD->isSynthesized())
867 if (Visit(MakeCXCursor(MD, TU)))
868 return true;
869
870 return false;
871}
872
Douglas Gregorb1373d02010-01-20 20:59:29 +0000873bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000874 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000875 if (D->getSuperClass() &&
876 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000877 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000878 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000879 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000880
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000881 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
882 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
883 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000884 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000885 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000886
Douglas Gregora59e3902010-01-21 23:27:09 +0000887 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000888}
889
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000890bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
891 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000892}
893
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000894bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000895 // 'ID' could be null when dealing with invalid code.
896 if (ObjCInterfaceDecl *ID = D->getClassInterface())
897 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
898 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000899
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000900 return VisitObjCImplDecl(D);
901}
902
903bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
904#if 0
905 // Issue callbacks for super class.
906 // FIXME: No source location information!
907 if (D->getSuperClass() &&
908 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000909 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000910 TU)))
911 return true;
912#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000913
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000914 return VisitObjCImplDecl(D);
915}
916
917bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
918 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
919 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
920 E = D->protocol_end();
921 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000922 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000923 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000924
925 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000926}
927
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000928bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
929 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
930 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
931 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000932
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000933 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000934}
935
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000936bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
937 return VisitDeclContext(D);
938}
939
Douglas Gregor69319002010-08-31 23:48:11 +0000940bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000941 // Visit nested-name-specifier.
942 if (NestedNameSpecifier *Qualifier = D->getQualifier())
943 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
944 return true;
Douglas Gregor69319002010-08-31 23:48:11 +0000945
946 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
947 D->getTargetNameLoc(), TU));
948}
949
Douglas Gregor7e242562010-09-01 19:52:22 +0000950bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000951 // Visit nested-name-specifier.
952 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
953 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
954 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +0000955
956 // FIXME: Provide a multi-reference of some kind for all of the declarations
957 // that the using declaration refers to. We don't have this kind of cursor
958 // yet.
959
960 return VisitDeclarationNameInfo(D->getNameInfo());
961}
962
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000963bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000964 // Visit nested-name-specifier.
965 if (NestedNameSpecifier *Qualifier = D->getQualifier())
966 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
967 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000968
969 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
970 D->getIdentLocation(), TU));
971}
972
Douglas Gregor7e242562010-09-01 19:52:22 +0000973bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000974 // Visit nested-name-specifier.
975 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
976 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
977 return true;
978
Douglas Gregor7e242562010-09-01 19:52:22 +0000979 return VisitDeclarationNameInfo(D->getNameInfo());
980}
981
982bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
983 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000984 // Visit nested-name-specifier.
985 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
986 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
987 return true;
988
Douglas Gregor7e242562010-09-01 19:52:22 +0000989 return false;
990}
991
Douglas Gregor01829d32010-08-31 14:41:23 +0000992bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
993 switch (Name.getName().getNameKind()) {
994 case clang::DeclarationName::Identifier:
995 case clang::DeclarationName::CXXLiteralOperatorName:
996 case clang::DeclarationName::CXXOperatorName:
997 case clang::DeclarationName::CXXUsingDirective:
998 return false;
999
1000 case clang::DeclarationName::CXXConstructorName:
1001 case clang::DeclarationName::CXXDestructorName:
1002 case clang::DeclarationName::CXXConversionFunctionName:
1003 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1004 return Visit(TSInfo->getTypeLoc());
1005 return false;
1006
1007 case clang::DeclarationName::ObjCZeroArgSelector:
1008 case clang::DeclarationName::ObjCOneArgSelector:
1009 case clang::DeclarationName::ObjCMultiArgSelector:
1010 // FIXME: Per-identifier location info?
1011 return false;
1012 }
1013
1014 return false;
1015}
1016
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001017bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1018 SourceRange Range) {
1019 // FIXME: This whole routine is a hack to work around the lack of proper
1020 // source information in nested-name-specifiers (PR5791). Since we do have
1021 // a beginning source location, we can visit the first component of the
1022 // nested-name-specifier, if it's a single-token component.
1023 if (!NNS)
1024 return false;
1025
1026 // Get the first component in the nested-name-specifier.
1027 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1028 NNS = Prefix;
1029
1030 switch (NNS->getKind()) {
1031 case NestedNameSpecifier::Namespace:
1032 // FIXME: The token at this source location might actually have been a
1033 // namespace alias, but we don't model that. Lame!
1034 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1035 TU));
1036
1037 case NestedNameSpecifier::TypeSpec: {
1038 // If the type has a form where we know that the beginning of the source
1039 // range matches up with a reference cursor. Visit the appropriate reference
1040 // cursor.
1041 Type *T = NNS->getAsType();
1042 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1043 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1044 if (const TagType *Tag = dyn_cast<TagType>(T))
1045 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1046 if (const TemplateSpecializationType *TST
1047 = dyn_cast<TemplateSpecializationType>(T))
1048 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1049 break;
1050 }
1051
1052 case NestedNameSpecifier::TypeSpecWithTemplate:
1053 case NestedNameSpecifier::Global:
1054 case NestedNameSpecifier::Identifier:
1055 break;
1056 }
1057
1058 return false;
1059}
1060
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001061bool CursorVisitor::VisitTemplateParameters(
1062 const TemplateParameterList *Params) {
1063 if (!Params)
1064 return false;
1065
1066 for (TemplateParameterList::const_iterator P = Params->begin(),
1067 PEnd = Params->end();
1068 P != PEnd; ++P) {
1069 if (Visit(MakeCXCursor(*P, TU)))
1070 return true;
1071 }
1072
1073 return false;
1074}
1075
Douglas Gregor0b36e612010-08-31 20:37:03 +00001076bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1077 switch (Name.getKind()) {
1078 case TemplateName::Template:
1079 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1080
1081 case TemplateName::OverloadedTemplate:
1082 // FIXME: We need a way to return multiple lookup results in a single
1083 // cursor.
1084 return false;
1085
1086 case TemplateName::DependentTemplate:
1087 // FIXME: Visit nested-name-specifier.
1088 return false;
1089
1090 case TemplateName::QualifiedTemplate:
1091 // FIXME: Visit nested-name-specifier.
1092 return Visit(MakeCursorTemplateRef(
1093 Name.getAsQualifiedTemplateName()->getDecl(),
1094 Loc, TU));
1095 }
1096
1097 return false;
1098}
1099
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001100bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1101 switch (TAL.getArgument().getKind()) {
1102 case TemplateArgument::Null:
1103 case TemplateArgument::Integral:
1104 return false;
1105
1106 case TemplateArgument::Pack:
1107 // FIXME: Implement when variadic templates come along.
1108 return false;
1109
1110 case TemplateArgument::Type:
1111 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1112 return Visit(TSInfo->getTypeLoc());
1113 return false;
1114
1115 case TemplateArgument::Declaration:
1116 if (Expr *E = TAL.getSourceDeclExpression())
1117 return Visit(MakeCXCursor(E, StmtParent, TU));
1118 return false;
1119
1120 case TemplateArgument::Expression:
1121 if (Expr *E = TAL.getSourceExpression())
1122 return Visit(MakeCXCursor(E, StmtParent, TU));
1123 return false;
1124
1125 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001126 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1127 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001128 }
1129
1130 return false;
1131}
1132
Ted Kremeneka0536d82010-05-07 01:04:29 +00001133bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1134 return VisitDeclContext(D);
1135}
1136
Douglas Gregor01829d32010-08-31 14:41:23 +00001137bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1138 return Visit(TL.getUnqualifiedLoc());
1139}
1140
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001141bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1142 ASTContext &Context = TU->getASTContext();
1143
1144 // Some builtin types (such as Objective-C's "id", "sel", and
1145 // "Class") have associated declarations. Create cursors for those.
1146 QualType VisitType;
1147 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001148 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001149 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001150 case BuiltinType::Char_U:
1151 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001152 case BuiltinType::Char16:
1153 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001154 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001155 case BuiltinType::UInt:
1156 case BuiltinType::ULong:
1157 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001158 case BuiltinType::UInt128:
1159 case BuiltinType::Char_S:
1160 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001161 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001162 case BuiltinType::Short:
1163 case BuiltinType::Int:
1164 case BuiltinType::Long:
1165 case BuiltinType::LongLong:
1166 case BuiltinType::Int128:
1167 case BuiltinType::Float:
1168 case BuiltinType::Double:
1169 case BuiltinType::LongDouble:
1170 case BuiltinType::NullPtr:
1171 case BuiltinType::Overload:
1172 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001173 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001174
1175 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001176 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001177
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001178 case BuiltinType::ObjCId:
1179 VisitType = Context.getObjCIdType();
1180 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001181
1182 case BuiltinType::ObjCClass:
1183 VisitType = Context.getObjCClassType();
1184 break;
1185
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001186 case BuiltinType::ObjCSel:
1187 VisitType = Context.getObjCSelType();
1188 break;
1189 }
1190
1191 if (!VisitType.isNull()) {
1192 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001193 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001194 TU));
1195 }
1196
1197 return false;
1198}
1199
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001200bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1201 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1202}
1203
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001204bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1205 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1206}
1207
1208bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1209 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1210}
1211
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001212bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1213 // FIXME: We can't visit the template template parameter, but there's
1214 // no context information with which we can match up the depth/index in the
1215 // type to the appropriate
1216 return false;
1217}
1218
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001219bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1220 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1221 return true;
1222
John McCallc12c5bb2010-05-15 11:32:37 +00001223 return false;
1224}
1225
1226bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1227 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1228 return true;
1229
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001230 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1231 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1232 TU)))
1233 return true;
1234 }
1235
1236 return false;
1237}
1238
1239bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001240 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001241}
1242
1243bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1244 return Visit(TL.getPointeeLoc());
1245}
1246
1247bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1248 return Visit(TL.getPointeeLoc());
1249}
1250
1251bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1252 return Visit(TL.getPointeeLoc());
1253}
1254
1255bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001256 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001257}
1258
1259bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001260 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001261}
1262
Douglas Gregor01829d32010-08-31 14:41:23 +00001263bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1264 bool SkipResultType) {
1265 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001266 return true;
1267
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001268 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001269 if (Decl *D = TL.getArg(I))
1270 if (Visit(MakeCXCursor(D, TU)))
1271 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001272
1273 return false;
1274}
1275
1276bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1277 if (Visit(TL.getElementLoc()))
1278 return true;
1279
1280 if (Expr *Size = TL.getSizeExpr())
1281 return Visit(MakeCXCursor(Size, StmtParent, TU));
1282
1283 return false;
1284}
1285
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001286bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1287 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001288 // Visit the template name.
1289 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1290 TL.getTemplateNameLoc()))
1291 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001292
1293 // Visit the template arguments.
1294 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1295 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1296 return true;
1297
1298 return false;
1299}
1300
Douglas Gregor2332c112010-01-21 20:48:56 +00001301bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1302 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1303}
1304
1305bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1306 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1307 return Visit(TSInfo->getTypeLoc());
1308
1309 return false;
1310}
1311
Douglas Gregora59e3902010-01-21 23:27:09 +00001312bool CursorVisitor::VisitStmt(Stmt *S) {
1313 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1314 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001315 if (Stmt *C = *Child)
1316 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1317 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001318 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001319
Douglas Gregora59e3902010-01-21 23:27:09 +00001320 return false;
1321}
1322
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001323bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1324 // Specially handle CaseStmts because they can be nested, e.g.:
1325 //
1326 // case 1:
1327 // case 2:
1328 //
1329 // In this case the second CaseStmt is the child of the first. Walking
1330 // these recursively can blow out the stack.
1331 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1332 while (true) {
1333 // Set the Parent field to Cursor, then back to its old value once we're
1334 // done.
1335 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1336
1337 if (Stmt *LHS = S->getLHS())
1338 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1339 return true;
1340 if (Stmt *RHS = S->getRHS())
1341 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1342 return true;
1343 if (Stmt *SubStmt = S->getSubStmt()) {
1344 if (!isa<CaseStmt>(SubStmt))
1345 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1346
1347 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1348 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1349 Cursor = MakeCXCursor(CS, StmtParent, TU);
1350 if (RegionOfInterest.isValid()) {
1351 SourceRange Range = CS->getSourceRange();
1352 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1353 return false;
1354 }
1355
1356 switch (Visitor(Cursor, Parent, ClientData)) {
1357 case CXChildVisit_Break: return true;
1358 case CXChildVisit_Continue: return false;
1359 case CXChildVisit_Recurse:
1360 // Perform tail-recursion manually.
1361 S = CS;
1362 continue;
1363 }
1364 }
1365 return false;
1366 }
1367}
1368
Douglas Gregora59e3902010-01-21 23:27:09 +00001369bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1370 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1371 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001372 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001373 return true;
1374 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001375
Douglas Gregora59e3902010-01-21 23:27:09 +00001376 return false;
1377}
1378
Douglas Gregorf5bab412010-01-22 01:00:11 +00001379bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1380 if (VarDecl *Var = S->getConditionVariable()) {
1381 if (Visit(MakeCXCursor(Var, TU)))
1382 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001383 }
1384
Douglas Gregor263b47b2010-01-25 16:12:32 +00001385 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1386 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001387 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1388 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001389 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1390 return true;
1391
1392 return false;
1393}
1394
1395bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1396 if (VarDecl *Var = S->getConditionVariable()) {
1397 if (Visit(MakeCXCursor(Var, TU)))
1398 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001399 }
1400
Douglas Gregor263b47b2010-01-25 16:12:32 +00001401 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1402 return true;
1403 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1404 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001405
Douglas Gregor263b47b2010-01-25 16:12:32 +00001406 return false;
1407}
1408
1409bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1410 if (VarDecl *Var = S->getConditionVariable()) {
1411 if (Visit(MakeCXCursor(Var, TU)))
1412 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001413 }
1414
Douglas Gregor263b47b2010-01-25 16:12:32 +00001415 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1416 return true;
1417 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001418 return true;
1419
Douglas Gregor263b47b2010-01-25 16:12:32 +00001420 return false;
1421}
1422
1423bool CursorVisitor::VisitForStmt(ForStmt *S) {
1424 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1425 return true;
1426 if (VarDecl *Var = S->getConditionVariable()) {
1427 if (Visit(MakeCXCursor(Var, TU)))
1428 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001429 }
1430
Douglas Gregor263b47b2010-01-25 16:12:32 +00001431 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1432 return true;
1433 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1434 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001435 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1436 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001437
Douglas Gregorf5bab412010-01-22 01:00:11 +00001438 return false;
1439}
1440
Douglas Gregor8947a752010-09-02 20:35:02 +00001441bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1442 // Visit nested-name-specifier, if present.
1443 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1444 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1445 return true;
1446
1447 // Visit declaration name.
1448 if (VisitDeclarationNameInfo(E->getNameInfo()))
1449 return true;
1450
1451 // Visit explicitly-specified template arguments.
1452 if (E->hasExplicitTemplateArgs()) {
1453 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1454 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1455 *ArgEnd = Arg + Args.NumTemplateArgs;
1456 Arg != ArgEnd; ++Arg)
1457 if (VisitTemplateArgumentLoc(*Arg))
1458 return true;
1459 }
1460
1461 return false;
1462}
1463
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001464bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1465 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1466 return true;
1467
1468 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1469 return true;
1470
1471 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1472 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1473 return true;
1474
1475 return false;
1476}
1477
Ted Kremenek3064ef92010-08-27 21:34:58 +00001478bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1479 if (D->isDefinition()) {
1480 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1481 E = D->bases_end(); I != E; ++I) {
1482 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1483 return true;
1484 }
1485 }
1486
1487 return VisitTagDecl(D);
1488}
1489
1490
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001491bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1492 return Visit(B->getBlockDecl());
1493}
1494
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001495bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1496 // FIXME: Visit fields as well?
1497 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1498 return true;
1499
1500 return VisitExpr(E);
1501}
1502
Douglas Gregor336fd812010-01-23 00:40:08 +00001503bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1504 if (E->isArgumentType()) {
1505 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1506 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001507
Douglas Gregor336fd812010-01-23 00:40:08 +00001508 return false;
1509 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001510
Douglas Gregor336fd812010-01-23 00:40:08 +00001511 return VisitExpr(E);
1512}
1513
1514bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1515 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1516 if (Visit(TSInfo->getTypeLoc()))
1517 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001518
Douglas Gregor336fd812010-01-23 00:40:08 +00001519 return VisitCastExpr(E);
1520}
1521
1522bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1523 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1524 if (Visit(TSInfo->getTypeLoc()))
1525 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001526
Douglas Gregor336fd812010-01-23 00:40:08 +00001527 return VisitExpr(E);
1528}
1529
Douglas Gregor648220e2010-08-10 15:02:34 +00001530bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1531 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1532 Visit(E->getArgTInfo2()->getTypeLoc());
1533}
1534
1535bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1536 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1537 return true;
1538
1539 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1540}
1541
Douglas Gregorc2350e52010-03-08 16:40:19 +00001542bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001543 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1544 if (Visit(TSInfo->getTypeLoc()))
1545 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001546
1547 return VisitExpr(E);
1548}
1549
Douglas Gregor81d34662010-04-20 15:39:42 +00001550bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1551 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1552}
1553
1554
Ted Kremenek09dfa372010-02-18 05:46:33 +00001555bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001556 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1557 i != e; ++i)
1558 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001559 return true;
1560
1561 return false;
1562}
1563
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001564extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001565CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1566 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001567 // We use crash recovery to make some of our APIs more reliable, implicitly
1568 // enable it.
1569 llvm::CrashRecoveryContext::Enable();
1570
Douglas Gregora030b7c2010-01-22 20:35:53 +00001571 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001572 if (excludeDeclarationsFromPCH)
1573 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001574 if (displayDiagnostics)
1575 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001576 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001577}
1578
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001579void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001580 if (CIdx)
1581 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001582 if (getenv("LIBCLANG_TIMING"))
1583 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001584}
1585
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001586void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001587 if (CIdx) {
1588 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1589 CXXIdx->setUseExternalASTGeneration(value);
1590 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001591}
1592
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001593CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001594 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001595 if (!CIdx)
1596 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001597
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001598 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001599
Douglas Gregor28019772010-04-05 23:52:57 +00001600 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001601 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001602 CXXIdx->getOnlyLocalDecls(),
1603 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001604}
1605
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001606unsigned clang_defaultEditingTranslationUnitOptions() {
1607 return CXTranslationUnit_PrecompiledPreamble;
1608}
1609
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001610CXTranslationUnit
1611clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1612 const char *source_filename,
1613 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001614 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001615 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001616 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001617 return clang_parseTranslationUnit(CIdx, source_filename,
1618 command_line_args, num_command_line_args,
1619 unsaved_files, num_unsaved_files,
1620 CXTranslationUnit_DetailedPreprocessingRecord);
1621}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001622
1623struct ParseTranslationUnitInfo {
1624 CXIndex CIdx;
1625 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001626 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001627 int num_command_line_args;
1628 struct CXUnsavedFile *unsaved_files;
1629 unsigned num_unsaved_files;
1630 unsigned options;
1631 CXTranslationUnit result;
1632};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001633static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001634 ParseTranslationUnitInfo *PTUI =
1635 static_cast<ParseTranslationUnitInfo*>(UserData);
1636 CXIndex CIdx = PTUI->CIdx;
1637 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00001638 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001639 int num_command_line_args = PTUI->num_command_line_args;
1640 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1641 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1642 unsigned options = PTUI->options;
1643 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001644
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001645 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001646 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001647
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001648 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1649
Douglas Gregor44c181a2010-07-23 00:33:23 +00001650 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001651 bool CompleteTranslationUnit
1652 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001653 bool CacheCodeCompetionResults
1654 = options & CXTranslationUnit_CacheCompletionResults;
1655
Douglas Gregor5352ac02010-01-28 00:27:43 +00001656 // Configure the diagnostics.
1657 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001658 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1659 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001660
Douglas Gregor4db64a42010-01-23 00:14:00 +00001661 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1662 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001663 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001664 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001665 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001666 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1667 Buffer));
1668 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001669
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001670 if (!CXXIdx->getUseExternalASTGeneration()) {
1671 llvm::SmallVector<const char *, 16> Args;
1672
1673 // The 'source_filename' argument is optional. If the caller does not
1674 // specify it then it is assumed that the source file is specified
1675 // in the actual argument list.
1676 if (source_filename)
1677 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001678
1679 // Since the Clang C library is primarily used by batch tools dealing with
1680 // (often very broken) source code, where spell-checking can have a
1681 // significant negative impact on performance (particularly when
1682 // precompiled headers are involved), we disable it by default.
1683 // Note that we place this argument early in the list, so that it can be
1684 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001685 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001686
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001687 Args.insert(Args.end(), command_line_args,
1688 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001689
Douglas Gregor44c181a2010-07-23 00:33:23 +00001690 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001691 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1692 Args.push_back("-Xclang");
1693 Args.push_back("-detailed-preprocessing-record");
1694 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001695
Douglas Gregor5352ac02010-01-28 00:27:43 +00001696 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001697
Ted Kremenek29b72842010-01-07 22:49:05 +00001698#ifdef USE_CRASHTRACER
1699 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001700#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001701
Daniel Dunbar94220972009-12-05 02:17:18 +00001702 llvm::OwningPtr<ASTUnit> Unit(
1703 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001704 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001705 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001706 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001707 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001708 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001709 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001710 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001711 CompleteTranslationUnit,
1712 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001713
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001714 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001715 // Make sure to check that 'Unit' is non-NULL.
1716 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001717 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1718 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001719 D != DEnd; ++D) {
1720 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001721 CXString Msg = clang_formatDiagnostic(&Diag,
1722 clang_defaultDiagnosticDisplayOptions());
1723 fprintf(stderr, "%s\n", clang_getCString(Msg));
1724 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001725 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001726#ifdef LLVM_ON_WIN32
1727 // On Windows, force a flush, since there may be multiple copies of
1728 // stderr and stdout in the file system, all with different buffers
1729 // but writing to the same device.
1730 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001731#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001732 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001733 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001734
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001735 PTUI->result = Unit.take();
1736 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001737 }
1738
Ted Kremenek139ba862009-10-22 00:03:57 +00001739 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001740 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001741
Ted Kremenek139ba862009-10-22 00:03:57 +00001742 // First add the complete path to the 'clang' executable.
1743 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001744 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001745
Ted Kremenek139ba862009-10-22 00:03:57 +00001746 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001747 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001748
Ted Kremenek139ba862009-10-22 00:03:57 +00001749 // The 'source_filename' argument is optional. If the caller does not
1750 // specify it then it is assumed that the source file is specified
1751 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001752 if (source_filename)
1753 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001754
Steve Naroff37b5ac22009-10-15 20:50:09 +00001755 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001756 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001757 char astTmpFile[L_tmpnam];
1758 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001759
1760 // Since the Clang C library is primarily used by batch tools dealing with
1761 // (often very broken) source code, where spell-checking can have a
1762 // significant negative impact on performance (particularly when
1763 // precompiled headers are involved), we disable it by default.
1764 // Note that we place this argument early in the list, so that it can be
1765 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001766 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001767
Douglas Gregor4db64a42010-01-23 00:14:00 +00001768 // Remap any unsaved files to temporary files.
1769 std::vector<llvm::sys::Path> TemporaryFiles;
1770 std::vector<std::string> RemapArgs;
1771 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001772 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001773
Douglas Gregor4db64a42010-01-23 00:14:00 +00001774 // The pointers into the elements of RemapArgs are stable because we
1775 // won't be adding anything to RemapArgs after this point.
1776 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1777 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001778
Ted Kremenek139ba862009-10-22 00:03:57 +00001779 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1780 for (int i = 0; i < num_command_line_args; ++i)
1781 if (const char *arg = command_line_args[i]) {
1782 if (strcmp(arg, "-o") == 0) {
1783 ++i; // Also skip the matching argument.
1784 continue;
1785 }
1786 if (strcmp(arg, "-emit-ast") == 0 ||
1787 strcmp(arg, "-c") == 0 ||
1788 strcmp(arg, "-fsyntax-only") == 0) {
1789 continue;
1790 }
1791
1792 // Keep the argument.
1793 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001794 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001795
Douglas Gregord93256e2010-01-28 06:00:51 +00001796 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001797 char tmpFileResults[L_tmpnam];
1798 char *tmpResultsFileName = tmpnam(tmpFileResults);
1799 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001800 TemporaryFiles.push_back(DiagnosticsFile);
1801 argv.push_back("-fdiagnostics-binary");
1802
Douglas Gregor44c181a2010-07-23 00:33:23 +00001803 // Do we need the detailed preprocessing record?
1804 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1805 argv.push_back("-Xclang");
1806 argv.push_back("-detailed-preprocessing-record");
1807 }
1808
Ted Kremenek139ba862009-10-22 00:03:57 +00001809 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001810 argv.push_back(NULL);
1811
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001812 // Invoke 'clang'.
1813 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1814 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001815 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001816 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1817 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001818 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001819 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001820 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001821
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001822 if (!ErrMsg.empty()) {
1823 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001824 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001825 I != E; ++I) {
1826 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001827 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001828 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001829 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001830
Daniel Dunbar32141c82010-02-23 20:23:45 +00001831 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001832 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001833
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001834 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001835 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001836 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001837 RemappedFiles.size(),
1838 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001839 if (ATU) {
1840 LoadSerializedDiagnostics(DiagnosticsFile,
1841 num_unsaved_files, unsaved_files,
1842 ATU->getFileManager(),
1843 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001844 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001845 } else if (CXXIdx->getDisplayDiagnostics()) {
1846 // We failed to load the ASTUnit, but we can still deserialize the
1847 // diagnostics and emit them.
1848 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001849 Diagnostic Diag;
1850 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001851 // FIXME: Faked LangOpts!
1852 LangOptions LangOpts;
1853 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1854 LoadSerializedDiagnostics(DiagnosticsFile,
1855 num_unsaved_files, unsaved_files,
1856 FileMgr, SourceMgr, Diags);
1857 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1858 DEnd = Diags.end();
1859 D != DEnd; ++D) {
1860 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001861 CXString Msg = clang_formatDiagnostic(&Diag,
1862 clang_defaultDiagnosticDisplayOptions());
1863 fprintf(stderr, "%s\n", clang_getCString(Msg));
1864 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001865 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001866
1867#ifdef LLVM_ON_WIN32
1868 // On Windows, force a flush, since there may be multiple copies of
1869 // stderr and stdout in the file system, all with different buffers
1870 // but writing to the same device.
1871 fflush(stderr);
1872#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001873 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001874
Douglas Gregor313e26c2010-02-18 23:35:40 +00001875 if (ATU) {
1876 // Make the translation unit responsible for destroying all temporary files.
1877 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1878 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001879 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001880 } else {
1881 // Destroy all of the temporary files now; they can't be referenced any
1882 // longer.
1883 llvm::sys::Path(astTmpFile).eraseFromDisk();
1884 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1885 TemporaryFiles[i].eraseFromDisk();
1886 }
1887
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001888 PTUI->result = ATU;
1889}
1890CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1891 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00001892 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001893 int num_command_line_args,
1894 struct CXUnsavedFile *unsaved_files,
1895 unsigned num_unsaved_files,
1896 unsigned options) {
1897 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1898 num_command_line_args, unsaved_files, num_unsaved_files,
1899 options, 0 };
1900 llvm::CrashRecoveryContext CRC;
1901
1902 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001903 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1904 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1905 fprintf(stderr, " 'command_line_args' : [");
1906 for (int i = 0; i != num_command_line_args; ++i) {
1907 if (i)
1908 fprintf(stderr, ", ");
1909 fprintf(stderr, "'%s'", command_line_args[i]);
1910 }
1911 fprintf(stderr, "],\n");
1912 fprintf(stderr, " 'unsaved_files' : [");
1913 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1914 if (i)
1915 fprintf(stderr, ", ");
1916 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1917 unsaved_files[i].Length);
1918 }
1919 fprintf(stderr, "],\n");
1920 fprintf(stderr, " 'options' : %d,\n", options);
1921 fprintf(stderr, "}\n");
1922
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001923 return 0;
1924 }
1925
1926 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001927}
1928
Douglas Gregor19998442010-08-13 15:35:05 +00001929unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1930 return CXSaveTranslationUnit_None;
1931}
1932
1933int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1934 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001935 if (!TU)
1936 return 1;
1937
1938 return static_cast<ASTUnit *>(TU)->Save(FileName);
1939}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001940
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001941void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001942 if (CTUnit) {
1943 // If the translation unit has been marked as unsafe to free, just discard
1944 // it.
1945 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1946 return;
1947
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001948 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001949 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001950}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001951
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001952unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1953 return CXReparse_None;
1954}
1955
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001956struct ReparseTranslationUnitInfo {
1957 CXTranslationUnit TU;
1958 unsigned num_unsaved_files;
1959 struct CXUnsavedFile *unsaved_files;
1960 unsigned options;
1961 int result;
1962};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001963static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001964 ReparseTranslationUnitInfo *RTUI =
1965 static_cast<ReparseTranslationUnitInfo*>(UserData);
1966 CXTranslationUnit TU = RTUI->TU;
1967 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1968 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1969 unsigned options = RTUI->options;
1970 (void) options;
1971 RTUI->result = 1;
1972
Douglas Gregorabc563f2010-07-19 21:46:24 +00001973 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001974 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001975
1976 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1977 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1978 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1979 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001980 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001981 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1982 Buffer));
1983 }
1984
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001985 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1986 RemappedFiles.size()))
1987 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001988}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001989int clang_reparseTranslationUnit(CXTranslationUnit TU,
1990 unsigned num_unsaved_files,
1991 struct CXUnsavedFile *unsaved_files,
1992 unsigned options) {
1993 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1994 options, 0 };
1995 llvm::CrashRecoveryContext CRC;
1996
1997 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001998 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001999 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2000 return 1;
2001 }
2002
2003 return RTUI.result;
2004}
2005
Douglas Gregordf95a132010-08-09 20:45:32 +00002006
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002007CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002008 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002009 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002010
Steve Naroff77accc12009-09-03 18:19:54 +00002011 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002012 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002013}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002014
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002015CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002016 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002017 return Result;
2018}
2019
Ted Kremenekfb480492010-01-13 21:46:36 +00002020} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002021
Ted Kremenekfb480492010-01-13 21:46:36 +00002022//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002023// CXSourceLocation and CXSourceRange Operations.
2024//===----------------------------------------------------------------------===//
2025
Douglas Gregorb9790342010-01-22 21:44:22 +00002026extern "C" {
2027CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002028 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002029 return Result;
2030}
2031
2032unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002033 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2034 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2035 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002036}
2037
2038CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2039 CXFile file,
2040 unsigned line,
2041 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002042 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002043 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002044
Douglas Gregorb9790342010-01-22 21:44:22 +00002045 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2046 SourceLocation SLoc
2047 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002048 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002049 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002050
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002051 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002052}
2053
Douglas Gregor5352ac02010-01-28 00:27:43 +00002054CXSourceRange clang_getNullRange() {
2055 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2056 return Result;
2057}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002058
Douglas Gregor5352ac02010-01-28 00:27:43 +00002059CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2060 if (begin.ptr_data[0] != end.ptr_data[0] ||
2061 begin.ptr_data[1] != end.ptr_data[1])
2062 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002063
2064 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002065 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002066 return Result;
2067}
2068
Douglas Gregor46766dc2010-01-26 19:19:08 +00002069void clang_getInstantiationLocation(CXSourceLocation location,
2070 CXFile *file,
2071 unsigned *line,
2072 unsigned *column,
2073 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002074 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2075
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002076 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002077 if (file)
2078 *file = 0;
2079 if (line)
2080 *line = 0;
2081 if (column)
2082 *column = 0;
2083 if (offset)
2084 *offset = 0;
2085 return;
2086 }
2087
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002088 const SourceManager &SM =
2089 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002090 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002091
2092 if (file)
2093 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2094 if (line)
2095 *line = SM.getInstantiationLineNumber(InstLoc);
2096 if (column)
2097 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002098 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002099 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002100}
2101
Douglas Gregor1db19de2010-01-19 21:36:55 +00002102CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002103 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002104 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002105 return Result;
2106}
2107
2108CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002109 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002110 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002111 return Result;
2112}
2113
Douglas Gregorb9790342010-01-22 21:44:22 +00002114} // end: extern "C"
2115
Douglas Gregor1db19de2010-01-19 21:36:55 +00002116//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002117// CXFile Operations.
2118//===----------------------------------------------------------------------===//
2119
2120extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002121CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002122 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002123 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002124
Steve Naroff88145032009-10-27 14:35:18 +00002125 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002126 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002127}
2128
2129time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002130 if (!SFile)
2131 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002132
Steve Naroff88145032009-10-27 14:35:18 +00002133 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2134 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002135}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002136
Douglas Gregorb9790342010-01-22 21:44:22 +00002137CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2138 if (!tu)
2139 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002140
Douglas Gregorb9790342010-01-22 21:44:22 +00002141 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002142
Douglas Gregorb9790342010-01-22 21:44:22 +00002143 FileManager &FMgr = CXXUnit->getFileManager();
2144 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2145 return const_cast<FileEntry *>(File);
2146}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002147
Ted Kremenekfb480492010-01-13 21:46:36 +00002148} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002149
Ted Kremenekfb480492010-01-13 21:46:36 +00002150//===----------------------------------------------------------------------===//
2151// CXCursor Operations.
2152//===----------------------------------------------------------------------===//
2153
Ted Kremenekfb480492010-01-13 21:46:36 +00002154static Decl *getDeclFromExpr(Stmt *E) {
2155 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2156 return RefExpr->getDecl();
2157 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2158 return ME->getMemberDecl();
2159 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2160 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002161
Ted Kremenekfb480492010-01-13 21:46:36 +00002162 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2163 return getDeclFromExpr(CE->getCallee());
2164 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2165 return getDeclFromExpr(CE->getSubExpr());
2166 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2167 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002168
Ted Kremenekfb480492010-01-13 21:46:36 +00002169 return 0;
2170}
2171
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002172static SourceLocation getLocationFromExpr(Expr *E) {
2173 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2174 return /*FIXME:*/Msg->getLeftLoc();
2175 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2176 return DRE->getLocation();
2177 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2178 return Member->getMemberLoc();
2179 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2180 return Ivar->getLocation();
2181 return E->getLocStart();
2182}
2183
Ted Kremenekfb480492010-01-13 21:46:36 +00002184extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002185
2186unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002187 CXCursorVisitor visitor,
2188 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002189 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002190
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002191 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2192 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002193 return CursorVis.VisitChildren(parent);
2194}
2195
Douglas Gregor78205d42010-01-20 21:45:58 +00002196static CXString getDeclSpelling(Decl *D) {
2197 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2198 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002199 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002200
Douglas Gregor78205d42010-01-20 21:45:58 +00002201 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002202 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002203
Douglas Gregor78205d42010-01-20 21:45:58 +00002204 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2205 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2206 // and returns different names. NamedDecl returns the class name and
2207 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002208 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002209
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002210 if (isa<UsingDirectiveDecl>(D))
2211 return createCXString("");
2212
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002213 llvm::SmallString<1024> S;
2214 llvm::raw_svector_ostream os(S);
2215 ND->printName(os);
2216
2217 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002218}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002219
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002220CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002221 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002222 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002223
Steve Narofff334b4e2009-09-02 18:26:48 +00002224 if (clang_isReference(C.kind)) {
2225 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002226 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002227 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002228 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002229 }
2230 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002231 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002232 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002233 }
2234 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002235 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002236 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002237 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002238 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002239 case CXCursor_CXXBaseSpecifier: {
2240 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2241 return createCXString(B->getType().getAsString());
2242 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002243 case CXCursor_TypeRef: {
2244 TypeDecl *Type = getCursorTypeRef(C).first;
2245 assert(Type && "Missing type decl");
2246
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002247 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2248 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002249 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002250 case CXCursor_TemplateRef: {
2251 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002252 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002253
2254 return createCXString(Template->getNameAsString());
2255 }
Douglas Gregor69319002010-08-31 23:48:11 +00002256
2257 case CXCursor_NamespaceRef: {
2258 NamedDecl *NS = getCursorNamespaceRef(C).first;
2259 assert(NS && "Missing namespace decl");
2260
2261 return createCXString(NS->getNameAsString());
2262 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002263
Daniel Dunbaracca7252009-11-30 20:42:49 +00002264 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002265 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002266 }
2267 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002268
2269 if (clang_isExpression(C.kind)) {
2270 Decl *D = getDeclFromExpr(getCursorExpr(C));
2271 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002272 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002273 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002274 }
2275
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002276 if (C.kind == CXCursor_MacroInstantiation)
2277 return createCXString(getCursorMacroInstantiation(C)->getName()
2278 ->getNameStart());
2279
Douglas Gregor572feb22010-03-18 18:04:21 +00002280 if (C.kind == CXCursor_MacroDefinition)
2281 return createCXString(getCursorMacroDefinition(C)->getName()
2282 ->getNameStart());
2283
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002284 if (clang_isDeclaration(C.kind))
2285 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002286
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002287 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002288}
2289
Ted Kremeneke68fff62010-02-17 00:41:32 +00002290CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002291 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002292 case CXCursor_FunctionDecl:
2293 return createCXString("FunctionDecl");
2294 case CXCursor_TypedefDecl:
2295 return createCXString("TypedefDecl");
2296 case CXCursor_EnumDecl:
2297 return createCXString("EnumDecl");
2298 case CXCursor_EnumConstantDecl:
2299 return createCXString("EnumConstantDecl");
2300 case CXCursor_StructDecl:
2301 return createCXString("StructDecl");
2302 case CXCursor_UnionDecl:
2303 return createCXString("UnionDecl");
2304 case CXCursor_ClassDecl:
2305 return createCXString("ClassDecl");
2306 case CXCursor_FieldDecl:
2307 return createCXString("FieldDecl");
2308 case CXCursor_VarDecl:
2309 return createCXString("VarDecl");
2310 case CXCursor_ParmDecl:
2311 return createCXString("ParmDecl");
2312 case CXCursor_ObjCInterfaceDecl:
2313 return createCXString("ObjCInterfaceDecl");
2314 case CXCursor_ObjCCategoryDecl:
2315 return createCXString("ObjCCategoryDecl");
2316 case CXCursor_ObjCProtocolDecl:
2317 return createCXString("ObjCProtocolDecl");
2318 case CXCursor_ObjCPropertyDecl:
2319 return createCXString("ObjCPropertyDecl");
2320 case CXCursor_ObjCIvarDecl:
2321 return createCXString("ObjCIvarDecl");
2322 case CXCursor_ObjCInstanceMethodDecl:
2323 return createCXString("ObjCInstanceMethodDecl");
2324 case CXCursor_ObjCClassMethodDecl:
2325 return createCXString("ObjCClassMethodDecl");
2326 case CXCursor_ObjCImplementationDecl:
2327 return createCXString("ObjCImplementationDecl");
2328 case CXCursor_ObjCCategoryImplDecl:
2329 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002330 case CXCursor_CXXMethod:
2331 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002332 case CXCursor_UnexposedDecl:
2333 return createCXString("UnexposedDecl");
2334 case CXCursor_ObjCSuperClassRef:
2335 return createCXString("ObjCSuperClassRef");
2336 case CXCursor_ObjCProtocolRef:
2337 return createCXString("ObjCProtocolRef");
2338 case CXCursor_ObjCClassRef:
2339 return createCXString("ObjCClassRef");
2340 case CXCursor_TypeRef:
2341 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002342 case CXCursor_TemplateRef:
2343 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002344 case CXCursor_NamespaceRef:
2345 return createCXString("NamespaceRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002346 case CXCursor_UnexposedExpr:
2347 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002348 case CXCursor_BlockExpr:
2349 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002350 case CXCursor_DeclRefExpr:
2351 return createCXString("DeclRefExpr");
2352 case CXCursor_MemberRefExpr:
2353 return createCXString("MemberRefExpr");
2354 case CXCursor_CallExpr:
2355 return createCXString("CallExpr");
2356 case CXCursor_ObjCMessageExpr:
2357 return createCXString("ObjCMessageExpr");
2358 case CXCursor_UnexposedStmt:
2359 return createCXString("UnexposedStmt");
2360 case CXCursor_InvalidFile:
2361 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002362 case CXCursor_InvalidCode:
2363 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002364 case CXCursor_NoDeclFound:
2365 return createCXString("NoDeclFound");
2366 case CXCursor_NotImplemented:
2367 return createCXString("NotImplemented");
2368 case CXCursor_TranslationUnit:
2369 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002370 case CXCursor_UnexposedAttr:
2371 return createCXString("UnexposedAttr");
2372 case CXCursor_IBActionAttr:
2373 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002374 case CXCursor_IBOutletAttr:
2375 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002376 case CXCursor_IBOutletCollectionAttr:
2377 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002378 case CXCursor_PreprocessingDirective:
2379 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002380 case CXCursor_MacroDefinition:
2381 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002382 case CXCursor_MacroInstantiation:
2383 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002384 case CXCursor_Namespace:
2385 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002386 case CXCursor_LinkageSpec:
2387 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002388 case CXCursor_CXXBaseSpecifier:
2389 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002390 case CXCursor_Constructor:
2391 return createCXString("CXXConstructor");
2392 case CXCursor_Destructor:
2393 return createCXString("CXXDestructor");
2394 case CXCursor_ConversionFunction:
2395 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002396 case CXCursor_TemplateTypeParameter:
2397 return createCXString("TemplateTypeParameter");
2398 case CXCursor_NonTypeTemplateParameter:
2399 return createCXString("NonTypeTemplateParameter");
2400 case CXCursor_TemplateTemplateParameter:
2401 return createCXString("TemplateTemplateParameter");
2402 case CXCursor_FunctionTemplate:
2403 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002404 case CXCursor_ClassTemplate:
2405 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002406 case CXCursor_ClassTemplatePartialSpecialization:
2407 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002408 case CXCursor_NamespaceAlias:
2409 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002410 case CXCursor_UsingDirective:
2411 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002412 case CXCursor_UsingDeclaration:
2413 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002414 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002415
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002416 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002417 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002418}
Steve Naroff89922f82009-08-31 00:59:03 +00002419
Ted Kremeneke68fff62010-02-17 00:41:32 +00002420enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2421 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002422 CXClientData client_data) {
2423 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2424 *BestCursor = cursor;
2425 return CXChildVisit_Recurse;
2426}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002427
Douglas Gregorb9790342010-01-22 21:44:22 +00002428CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2429 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002430 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002431
Douglas Gregorb9790342010-01-22 21:44:22 +00002432 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002433 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2434
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002435 // Translate the given source location to make it point at the beginning of
2436 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002437 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002438
2439 // Guard against an invalid SourceLocation, or we may assert in one
2440 // of the following calls.
2441 if (SLoc.isInvalid())
2442 return clang_getNullCursor();
2443
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002444 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2445 CXXUnit->getASTContext().getLangOptions());
2446
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002447 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2448 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002449 // FIXME: Would be great to have a "hint" cursor, then walk from that
2450 // hint cursor upward until we find a cursor whose source range encloses
2451 // the region of interest, rather than starting from the translation unit.
2452 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002453 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002454 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002455 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002456 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002457 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002458}
2459
Ted Kremenek73885552009-11-17 19:28:59 +00002460CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002461 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002462}
2463
2464unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002465 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002466}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002467
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002468unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002469 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2470}
2471
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002472unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002473 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2474}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002475
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002476unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002477 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2478}
2479
Douglas Gregor97b98722010-01-19 23:20:36 +00002480unsigned clang_isExpression(enum CXCursorKind K) {
2481 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2482}
2483
2484unsigned clang_isStatement(enum CXCursorKind K) {
2485 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2486}
2487
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002488unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2489 return K == CXCursor_TranslationUnit;
2490}
2491
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002492unsigned clang_isPreprocessing(enum CXCursorKind K) {
2493 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2494}
2495
Ted Kremenekad6eff62010-03-08 21:17:29 +00002496unsigned clang_isUnexposed(enum CXCursorKind K) {
2497 switch (K) {
2498 case CXCursor_UnexposedDecl:
2499 case CXCursor_UnexposedExpr:
2500 case CXCursor_UnexposedStmt:
2501 case CXCursor_UnexposedAttr:
2502 return true;
2503 default:
2504 return false;
2505 }
2506}
2507
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002508CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002509 return C.kind;
2510}
2511
Douglas Gregor98258af2010-01-18 22:46:11 +00002512CXSourceLocation clang_getCursorLocation(CXCursor C) {
2513 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002514 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002515 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002516 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2517 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002518 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002519 }
2520
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002521 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002522 std::pair<ObjCProtocolDecl *, SourceLocation> P
2523 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002524 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002525 }
2526
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002527 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002528 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2529 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002530 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002531 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002532
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002533 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002534 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002535 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002536 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002537
2538 case CXCursor_TemplateRef: {
2539 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2540 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2541 }
2542
Douglas Gregor69319002010-08-31 23:48:11 +00002543 case CXCursor_NamespaceRef: {
2544 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2545 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2546 }
2547
Ted Kremenek3064ef92010-08-27 21:34:58 +00002548 case CXCursor_CXXBaseSpecifier: {
2549 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2550 return clang_getNullLocation();
2551 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002552
Douglas Gregorf46034a2010-01-18 23:41:10 +00002553 default:
2554 // FIXME: Need a way to enumerate all non-reference cases.
2555 llvm_unreachable("Missed a reference kind");
2556 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002557 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002558
2559 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002560 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002561 getLocationFromExpr(getCursorExpr(C)));
2562
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002563 if (C.kind == CXCursor_PreprocessingDirective) {
2564 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2565 return cxloc::translateSourceLocation(getCursorContext(C), L);
2566 }
Douglas Gregor48072312010-03-18 15:23:44 +00002567
2568 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002569 SourceLocation L
2570 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002571 return cxloc::translateSourceLocation(getCursorContext(C), L);
2572 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002573
2574 if (C.kind == CXCursor_MacroDefinition) {
2575 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2576 return cxloc::translateSourceLocation(getCursorContext(C), L);
2577 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002578
Ted Kremenek9a700d22010-05-12 06:16:13 +00002579 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002580 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002581
Douglas Gregorf46034a2010-01-18 23:41:10 +00002582 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002583 SourceLocation Loc = D->getLocation();
2584 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2585 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002586 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002587}
Douglas Gregora7bde202010-01-19 00:34:46 +00002588
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002589} // end extern "C"
2590
2591static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002592 if (clang_isReference(C.kind)) {
2593 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002594 case CXCursor_ObjCSuperClassRef:
2595 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002596
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002597 case CXCursor_ObjCProtocolRef:
2598 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002599
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002600 case CXCursor_ObjCClassRef:
2601 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002602
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002603 case CXCursor_TypeRef:
2604 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002605
2606 case CXCursor_TemplateRef:
2607 return getCursorTemplateRef(C).second;
2608
Douglas Gregor69319002010-08-31 23:48:11 +00002609 case CXCursor_NamespaceRef:
2610 return getCursorNamespaceRef(C).second;
2611
Ted Kremenek3064ef92010-08-27 21:34:58 +00002612 case CXCursor_CXXBaseSpecifier:
2613 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2614 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002615
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002616 default:
2617 // FIXME: Need a way to enumerate all non-reference cases.
2618 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002619 }
2620 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002621
2622 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002623 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002624
2625 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002626 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002627
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002628 if (C.kind == CXCursor_PreprocessingDirective)
2629 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002630
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002631 if (C.kind == CXCursor_MacroInstantiation)
2632 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002633
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002634 if (C.kind == CXCursor_MacroDefinition)
2635 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002636
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002637 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2638 return getCursorDecl(C)->getSourceRange();
2639
2640 return SourceRange();
2641}
2642
2643extern "C" {
2644
2645CXSourceRange clang_getCursorExtent(CXCursor C) {
2646 SourceRange R = getRawCursorExtent(C);
2647 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002648 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002649
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002650 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002651}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002652
2653CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002654 if (clang_isInvalid(C.kind))
2655 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002656
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002657 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002658 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002659 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002660
Douglas Gregor97b98722010-01-19 23:20:36 +00002661 if (clang_isExpression(C.kind)) {
2662 Decl *D = getDeclFromExpr(getCursorExpr(C));
2663 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002664 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002665 return clang_getNullCursor();
2666 }
2667
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002668 if (C.kind == CXCursor_MacroInstantiation) {
2669 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2670 return MakeMacroDefinitionCursor(Def, CXXUnit);
2671 }
2672
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002673 if (!clang_isReference(C.kind))
2674 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002675
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002676 switch (C.kind) {
2677 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002678 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002679
2680 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002681 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002682
2683 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002684 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002685
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002686 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002687 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002688
2689 case CXCursor_TemplateRef:
2690 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2691
Douglas Gregor69319002010-08-31 23:48:11 +00002692 case CXCursor_NamespaceRef:
2693 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2694
Ted Kremenek3064ef92010-08-27 21:34:58 +00002695 case CXCursor_CXXBaseSpecifier: {
2696 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2697 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2698 CXXUnit));
2699 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002700
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002701 default:
2702 // We would prefer to enumerate all non-reference cursor kinds here.
2703 llvm_unreachable("Unhandled reference cursor kind");
2704 break;
2705 }
2706 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002707
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002708 return clang_getNullCursor();
2709}
2710
Douglas Gregorb6998662010-01-19 19:34:47 +00002711CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002712 if (clang_isInvalid(C.kind))
2713 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002714
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002715 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002716
Douglas Gregorb6998662010-01-19 19:34:47 +00002717 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002718 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002719 C = clang_getCursorReferenced(C);
2720 WasReference = true;
2721 }
2722
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002723 if (C.kind == CXCursor_MacroInstantiation)
2724 return clang_getCursorReferenced(C);
2725
Douglas Gregorb6998662010-01-19 19:34:47 +00002726 if (!clang_isDeclaration(C.kind))
2727 return clang_getNullCursor();
2728
2729 Decl *D = getCursorDecl(C);
2730 if (!D)
2731 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002732
Douglas Gregorb6998662010-01-19 19:34:47 +00002733 switch (D->getKind()) {
2734 // Declaration kinds that don't really separate the notions of
2735 // declaration and definition.
2736 case Decl::Namespace:
2737 case Decl::Typedef:
2738 case Decl::TemplateTypeParm:
2739 case Decl::EnumConstant:
2740 case Decl::Field:
2741 case Decl::ObjCIvar:
2742 case Decl::ObjCAtDefsField:
2743 case Decl::ImplicitParam:
2744 case Decl::ParmVar:
2745 case Decl::NonTypeTemplateParm:
2746 case Decl::TemplateTemplateParm:
2747 case Decl::ObjCCategoryImpl:
2748 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002749 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002750 case Decl::LinkageSpec:
2751 case Decl::ObjCPropertyImpl:
2752 case Decl::FileScopeAsm:
2753 case Decl::StaticAssert:
2754 case Decl::Block:
2755 return C;
2756
2757 // Declaration kinds that don't make any sense here, but are
2758 // nonetheless harmless.
2759 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002760 break;
2761
2762 // Declaration kinds for which the definition is not resolvable.
2763 case Decl::UnresolvedUsingTypename:
2764 case Decl::UnresolvedUsingValue:
2765 break;
2766
2767 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002768 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2769 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002770
2771 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002772 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002773
2774 case Decl::Enum:
2775 case Decl::Record:
2776 case Decl::CXXRecord:
2777 case Decl::ClassTemplateSpecialization:
2778 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002779 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002780 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002781 return clang_getNullCursor();
2782
2783 case Decl::Function:
2784 case Decl::CXXMethod:
2785 case Decl::CXXConstructor:
2786 case Decl::CXXDestructor:
2787 case Decl::CXXConversion: {
2788 const FunctionDecl *Def = 0;
2789 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002790 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002791 return clang_getNullCursor();
2792 }
2793
2794 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002795 // Ask the variable if it has a definition.
2796 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2797 return MakeCXCursor(Def, CXXUnit);
2798 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002799 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002800
Douglas Gregorb6998662010-01-19 19:34:47 +00002801 case Decl::FunctionTemplate: {
2802 const FunctionDecl *Def = 0;
2803 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002804 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002805 return clang_getNullCursor();
2806 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002807
Douglas Gregorb6998662010-01-19 19:34:47 +00002808 case Decl::ClassTemplate: {
2809 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002810 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002811 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002812 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002813 return clang_getNullCursor();
2814 }
2815
2816 case Decl::Using: {
2817 UsingDecl *Using = cast<UsingDecl>(D);
2818 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002819 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2820 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002821 S != SEnd; ++S) {
2822 if (Def != clang_getNullCursor()) {
2823 // FIXME: We have no way to return multiple results.
2824 return clang_getNullCursor();
2825 }
2826
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002827 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002828 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002829 }
2830
2831 return Def;
2832 }
2833
2834 case Decl::UsingShadow:
2835 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002836 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002837 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002838
2839 case Decl::ObjCMethod: {
2840 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2841 if (Method->isThisDeclarationADefinition())
2842 return C;
2843
2844 // Dig out the method definition in the associated
2845 // @implementation, if we have it.
2846 // FIXME: The ASTs should make finding the definition easier.
2847 if (ObjCInterfaceDecl *Class
2848 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2849 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2850 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2851 Method->isInstanceMethod()))
2852 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002853 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002854
2855 return clang_getNullCursor();
2856 }
2857
2858 case Decl::ObjCCategory:
2859 if (ObjCCategoryImplDecl *Impl
2860 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002861 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002862 return clang_getNullCursor();
2863
2864 case Decl::ObjCProtocol:
2865 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2866 return C;
2867 return clang_getNullCursor();
2868
2869 case Decl::ObjCInterface:
2870 // There are two notions of a "definition" for an Objective-C
2871 // class: the interface and its implementation. When we resolved a
2872 // reference to an Objective-C class, produce the @interface as
2873 // the definition; when we were provided with the interface,
2874 // produce the @implementation as the definition.
2875 if (WasReference) {
2876 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2877 return C;
2878 } else if (ObjCImplementationDecl *Impl
2879 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002880 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002881 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002882
Douglas Gregorb6998662010-01-19 19:34:47 +00002883 case Decl::ObjCProperty:
2884 // FIXME: We don't really know where to find the
2885 // ObjCPropertyImplDecls that implement this property.
2886 return clang_getNullCursor();
2887
2888 case Decl::ObjCCompatibleAlias:
2889 if (ObjCInterfaceDecl *Class
2890 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2891 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002892 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002893
Douglas Gregorb6998662010-01-19 19:34:47 +00002894 return clang_getNullCursor();
2895
2896 case Decl::ObjCForwardProtocol: {
2897 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2898 if (Forward->protocol_size() == 1)
2899 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002900 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002901 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002902
2903 // FIXME: Cannot return multiple definitions.
2904 return clang_getNullCursor();
2905 }
2906
2907 case Decl::ObjCClass: {
2908 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2909 if (Class->size() == 1) {
2910 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2911 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002912 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002913 return clang_getNullCursor();
2914 }
2915
2916 // FIXME: Cannot return multiple definitions.
2917 return clang_getNullCursor();
2918 }
2919
2920 case Decl::Friend:
2921 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002922 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002923 return clang_getNullCursor();
2924
2925 case Decl::FriendTemplate:
2926 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002927 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002928 return clang_getNullCursor();
2929 }
2930
2931 return clang_getNullCursor();
2932}
2933
2934unsigned clang_isCursorDefinition(CXCursor C) {
2935 if (!clang_isDeclaration(C.kind))
2936 return 0;
2937
2938 return clang_getCursorDefinition(C) == C;
2939}
2940
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002941void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002942 const char **startBuf,
2943 const char **endBuf,
2944 unsigned *startLine,
2945 unsigned *startColumn,
2946 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002947 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002948 assert(getCursorDecl(C) && "CXCursor has null decl");
2949 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002950 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2951 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002952
Steve Naroff4ade6d62009-09-23 17:52:52 +00002953 SourceManager &SM = FD->getASTContext().getSourceManager();
2954 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2955 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2956 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2957 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2958 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2959 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2960}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002961
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002962void clang_enableStackTraces(void) {
2963 llvm::sys::PrintStackTraceOnErrorSignal();
2964}
2965
Ted Kremenekfb480492010-01-13 21:46:36 +00002966} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002967
Ted Kremenekfb480492010-01-13 21:46:36 +00002968//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002969// Token-based Operations.
2970//===----------------------------------------------------------------------===//
2971
2972/* CXToken layout:
2973 * int_data[0]: a CXTokenKind
2974 * int_data[1]: starting token location
2975 * int_data[2]: token length
2976 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002977 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002978 * otherwise unused.
2979 */
2980extern "C" {
2981
2982CXTokenKind clang_getTokenKind(CXToken CXTok) {
2983 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2984}
2985
2986CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2987 switch (clang_getTokenKind(CXTok)) {
2988 case CXToken_Identifier:
2989 case CXToken_Keyword:
2990 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002991 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2992 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002993
2994 case CXToken_Literal: {
2995 // We have stashed the starting pointer in the ptr_data field. Use it.
2996 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002997 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002998 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002999
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003000 case CXToken_Punctuation:
3001 case CXToken_Comment:
3002 break;
3003 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003004
3005 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003006 // deconstructing the source location.
3007 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3008 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003009 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003010
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003011 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3012 std::pair<FileID, unsigned> LocInfo
3013 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003014 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003015 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003016 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3017 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003018 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003019
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003020 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003021}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003022
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003023CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3024 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3025 if (!CXXUnit)
3026 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003027
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003028 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3029 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3030}
3031
3032CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3033 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003034 if (!CXXUnit)
3035 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003036
3037 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003038 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3039}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003040
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003041void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3042 CXToken **Tokens, unsigned *NumTokens) {
3043 if (Tokens)
3044 *Tokens = 0;
3045 if (NumTokens)
3046 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003047
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003048 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3049 if (!CXXUnit || !Tokens || !NumTokens)
3050 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003051
Douglas Gregorbdf60622010-03-05 21:16:25 +00003052 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3053
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003054 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003055 if (R.isInvalid())
3056 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003057
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003058 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3059 std::pair<FileID, unsigned> BeginLocInfo
3060 = SourceMgr.getDecomposedLoc(R.getBegin());
3061 std::pair<FileID, unsigned> EndLocInfo
3062 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003063
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003064 // Cannot tokenize across files.
3065 if (BeginLocInfo.first != EndLocInfo.first)
3066 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003067
3068 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003069 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003070 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003071 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003072 if (Invalid)
3073 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003074
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003075 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3076 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003077 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003078 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003079
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003080 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003081 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003082 llvm::SmallVector<CXToken, 32> CXTokens;
3083 Token Tok;
3084 do {
3085 // Lex the next token
3086 Lex.LexFromRawLexer(Tok);
3087 if (Tok.is(tok::eof))
3088 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003089
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003090 // Initialize the CXToken.
3091 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003092
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003093 // - Common fields
3094 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3095 CXTok.int_data[2] = Tok.getLength();
3096 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003097
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003098 // - Kind-specific fields
3099 if (Tok.isLiteral()) {
3100 CXTok.int_data[0] = CXToken_Literal;
3101 CXTok.ptr_data = (void *)Tok.getLiteralData();
3102 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003103 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003104 std::pair<FileID, unsigned> LocInfo
3105 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003106 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003107 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003108 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3109 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003110 return;
3111
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003112 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003113 IdentifierInfo *II
3114 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003115
3116 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3117 CXTok.int_data[0] = CXToken_Keyword;
3118 }
3119 else {
3120 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3121 CXToken_Identifier
3122 : CXToken_Keyword;
3123 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003124 CXTok.ptr_data = II;
3125 } else if (Tok.is(tok::comment)) {
3126 CXTok.int_data[0] = CXToken_Comment;
3127 CXTok.ptr_data = 0;
3128 } else {
3129 CXTok.int_data[0] = CXToken_Punctuation;
3130 CXTok.ptr_data = 0;
3131 }
3132 CXTokens.push_back(CXTok);
3133 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003134
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003135 if (CXTokens.empty())
3136 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003137
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003138 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3139 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3140 *NumTokens = CXTokens.size();
3141}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003142
Ted Kremenek6db61092010-05-05 00:55:15 +00003143void clang_disposeTokens(CXTranslationUnit TU,
3144 CXToken *Tokens, unsigned NumTokens) {
3145 free(Tokens);
3146}
3147
3148} // end: extern "C"
3149
3150//===----------------------------------------------------------------------===//
3151// Token annotation APIs.
3152//===----------------------------------------------------------------------===//
3153
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003154typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003155static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3156 CXCursor parent,
3157 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003158namespace {
3159class AnnotateTokensWorker {
3160 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003161 CXToken *Tokens;
3162 CXCursor *Cursors;
3163 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003164 unsigned TokIdx;
3165 CursorVisitor AnnotateVis;
3166 SourceManager &SrcMgr;
3167
3168 bool MoreTokens() const { return TokIdx < NumTokens; }
3169 unsigned NextToken() const { return TokIdx; }
3170 void AdvanceToken() { ++TokIdx; }
3171 SourceLocation GetTokenLoc(unsigned tokI) {
3172 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3173 }
3174
Ted Kremenek6db61092010-05-05 00:55:15 +00003175public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003176 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003177 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3178 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003179 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003180 NumTokens(numTokens), TokIdx(0),
3181 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3182 Decl::MaxPCHLevel, RegionOfInterest),
3183 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003184
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003185 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003186 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003187 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003188};
3189}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003190
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003191void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3192 // Walk the AST within the region of interest, annotating tokens
3193 // along the way.
3194 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003195
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003196 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3197 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3198 if (Pos != Annotated.end())
3199 Cursors[I] = Pos->second;
3200 }
3201
3202 // Finish up annotating any tokens left.
3203 if (!MoreTokens())
3204 return;
3205
3206 const CXCursor &C = clang_getNullCursor();
3207 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3208 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3209 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003210 }
3211}
3212
Ted Kremenek6db61092010-05-05 00:55:15 +00003213enum CXChildVisitResult
3214AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003215 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3216 // We can always annotate a preprocessing directive/macro instantiation.
3217 if (clang_isPreprocessing(cursor.kind)) {
3218 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003219 return CXChildVisit_Recurse;
3220 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003221
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003222 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003223
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003224 if (cursorRange.isInvalid())
3225 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003226
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003227 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3228
Ted Kremeneka333c662010-05-12 05:29:33 +00003229 // Adjust the annotated range based specific declarations.
3230 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3231 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003232 Decl *D = cxcursor::getCursorDecl(cursor);
3233 // Don't visit synthesized ObjC methods, since they have no syntatic
3234 // representation in the source.
3235 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3236 if (MD->isSynthesized())
3237 return CXChildVisit_Continue;
3238 }
3239 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003240 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3241 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003242 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003243 if (TLoc.isValid() &&
3244 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003245 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003246 }
3247 }
3248 }
3249
Ted Kremenek3f404602010-08-14 01:14:06 +00003250 // If the location of the cursor occurs within a macro instantiation, record
3251 // the spelling location of the cursor in our annotation map. We can then
3252 // paper over the token labelings during a post-processing step to try and
3253 // get cursor mappings for tokens that are the *arguments* of a macro
3254 // instantiation.
3255 if (L.isMacroID()) {
3256 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3257 // Only invalidate the old annotation if it isn't part of a preprocessing
3258 // directive. Here we assume that the default construction of CXCursor
3259 // results in CXCursor.kind being an initialized value (i.e., 0). If
3260 // this isn't the case, we can fix by doing lookup + insertion.
3261
3262 CXCursor &oldC = Annotated[rawEncoding];
3263 if (!clang_isPreprocessing(oldC.kind))
3264 oldC = cursor;
3265 }
3266
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003267 const enum CXCursorKind K = clang_getCursorKind(parent);
3268 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003269 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3270 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003271
3272 while (MoreTokens()) {
3273 const unsigned I = NextToken();
3274 SourceLocation TokLoc = GetTokenLoc(I);
3275 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3276 case RangeBefore:
3277 Cursors[I] = updateC;
3278 AdvanceToken();
3279 continue;
3280 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003281 case RangeOverlap:
3282 break;
3283 }
3284 break;
3285 }
3286
3287 // Visit children to get their cursor information.
3288 const unsigned BeforeChildren = NextToken();
3289 VisitChildren(cursor);
3290 const unsigned AfterChildren = NextToken();
3291
3292 // Adjust 'Last' to the last token within the extent of the cursor.
3293 while (MoreTokens()) {
3294 const unsigned I = NextToken();
3295 SourceLocation TokLoc = GetTokenLoc(I);
3296 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3297 case RangeBefore:
3298 assert(0 && "Infeasible");
3299 case RangeAfter:
3300 break;
3301 case RangeOverlap:
3302 Cursors[I] = updateC;
3303 AdvanceToken();
3304 continue;
3305 }
3306 break;
3307 }
3308 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003309
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003310 // Scan the tokens that are at the beginning of the cursor, but are not
3311 // capture by the child cursors.
3312
3313 // For AST elements within macros, rely on a post-annotate pass to
3314 // to correctly annotate the tokens with cursors. Otherwise we can
3315 // get confusing results of having tokens that map to cursors that really
3316 // are expanded by an instantiation.
3317 if (L.isMacroID())
3318 cursor = clang_getNullCursor();
3319
3320 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3321 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3322 break;
3323 Cursors[I] = cursor;
3324 }
3325 // Scan the tokens that are at the end of the cursor, but are not captured
3326 // but the child cursors.
3327 for (unsigned I = AfterChildren; I != Last; ++I)
3328 Cursors[I] = cursor;
3329
3330 TokIdx = Last;
3331 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003332}
3333
Ted Kremenek6db61092010-05-05 00:55:15 +00003334static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3335 CXCursor parent,
3336 CXClientData client_data) {
3337 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3338}
3339
3340extern "C" {
3341
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003342void clang_annotateTokens(CXTranslationUnit TU,
3343 CXToken *Tokens, unsigned NumTokens,
3344 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003345
3346 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003347 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003348
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003349 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003350 if (!CXXUnit) {
3351 // Any token we don't specifically annotate will have a NULL cursor.
3352 const CXCursor &C = clang_getNullCursor();
3353 for (unsigned I = 0; I != NumTokens; ++I)
3354 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003355 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003356 }
3357
Douglas Gregorbdf60622010-03-05 21:16:25 +00003358 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003359
Douglas Gregor0396f462010-03-19 05:22:59 +00003360 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003361 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003362 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3363 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003364 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3365 clang_getTokenLocation(TU,
3366 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003367
Douglas Gregor0396f462010-03-19 05:22:59 +00003368 // A mapping from the source locations found when re-lexing or traversing the
3369 // region of interest to the corresponding cursors.
3370 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003371
3372 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003373 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003374 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3375 std::pair<FileID, unsigned> BeginLocInfo
3376 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3377 std::pair<FileID, unsigned> EndLocInfo
3378 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003379
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003380 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003381 bool Invalid = false;
3382 if (BeginLocInfo.first == EndLocInfo.first &&
3383 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3384 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003385 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3386 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003387 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003388 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003389 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003390
3391 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003392 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003393 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003394 Token Tok;
3395 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003396
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003397 reprocess:
3398 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3399 // We have found a preprocessing directive. Gobble it up so that we
3400 // don't see it while preprocessing these tokens later, but keep track of
3401 // all of the token locations inside this preprocessing directive so that
3402 // we can annotate them appropriately.
3403 //
3404 // FIXME: Some simple tests here could identify macro definitions and
3405 // #undefs, to provide specific cursor kinds for those.
3406 std::vector<SourceLocation> Locations;
3407 do {
3408 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003409 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003410 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003411
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003412 using namespace cxcursor;
3413 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003414 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3415 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003416 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003417 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3418 Annotated[Locations[I].getRawEncoding()] = Cursor;
3419 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003420
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003421 if (Tok.isAtStartOfLine())
3422 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003423
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003424 continue;
3425 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003426
Douglas Gregor48072312010-03-18 15:23:44 +00003427 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003428 break;
3429 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003430 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003431
Douglas Gregor0396f462010-03-19 05:22:59 +00003432 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003433 // a specific cursor.
3434 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3435 CXXUnit, RegionOfInterest);
3436 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003437}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003438} // end: extern "C"
3439
3440//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003441// Operations for querying linkage of a cursor.
3442//===----------------------------------------------------------------------===//
3443
3444extern "C" {
3445CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003446 if (!clang_isDeclaration(cursor.kind))
3447 return CXLinkage_Invalid;
3448
Ted Kremenek16b42592010-03-03 06:36:57 +00003449 Decl *D = cxcursor::getCursorDecl(cursor);
3450 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3451 switch (ND->getLinkage()) {
3452 case NoLinkage: return CXLinkage_NoLinkage;
3453 case InternalLinkage: return CXLinkage_Internal;
3454 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3455 case ExternalLinkage: return CXLinkage_External;
3456 };
3457
3458 return CXLinkage_Invalid;
3459}
3460} // end: extern "C"
3461
3462//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003463// Operations for querying language of a cursor.
3464//===----------------------------------------------------------------------===//
3465
3466static CXLanguageKind getDeclLanguage(const Decl *D) {
3467 switch (D->getKind()) {
3468 default:
3469 break;
3470 case Decl::ImplicitParam:
3471 case Decl::ObjCAtDefsField:
3472 case Decl::ObjCCategory:
3473 case Decl::ObjCCategoryImpl:
3474 case Decl::ObjCClass:
3475 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003476 case Decl::ObjCForwardProtocol:
3477 case Decl::ObjCImplementation:
3478 case Decl::ObjCInterface:
3479 case Decl::ObjCIvar:
3480 case Decl::ObjCMethod:
3481 case Decl::ObjCProperty:
3482 case Decl::ObjCPropertyImpl:
3483 case Decl::ObjCProtocol:
3484 return CXLanguage_ObjC;
3485 case Decl::CXXConstructor:
3486 case Decl::CXXConversion:
3487 case Decl::CXXDestructor:
3488 case Decl::CXXMethod:
3489 case Decl::CXXRecord:
3490 case Decl::ClassTemplate:
3491 case Decl::ClassTemplatePartialSpecialization:
3492 case Decl::ClassTemplateSpecialization:
3493 case Decl::Friend:
3494 case Decl::FriendTemplate:
3495 case Decl::FunctionTemplate:
3496 case Decl::LinkageSpec:
3497 case Decl::Namespace:
3498 case Decl::NamespaceAlias:
3499 case Decl::NonTypeTemplateParm:
3500 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003501 case Decl::TemplateTemplateParm:
3502 case Decl::TemplateTypeParm:
3503 case Decl::UnresolvedUsingTypename:
3504 case Decl::UnresolvedUsingValue:
3505 case Decl::Using:
3506 case Decl::UsingDirective:
3507 case Decl::UsingShadow:
3508 return CXLanguage_CPlusPlus;
3509 }
3510
3511 return CXLanguage_C;
3512}
3513
3514extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003515
3516enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3517 if (clang_isDeclaration(cursor.kind))
3518 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3519 if (D->hasAttr<UnavailableAttr>() ||
3520 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3521 return CXAvailability_Available;
3522
3523 if (D->hasAttr<DeprecatedAttr>())
3524 return CXAvailability_Deprecated;
3525 }
3526
3527 return CXAvailability_Available;
3528}
3529
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003530CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3531 if (clang_isDeclaration(cursor.kind))
3532 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3533
3534 return CXLanguage_Invalid;
3535}
3536} // end: extern "C"
3537
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003538
3539//===----------------------------------------------------------------------===//
3540// C++ AST instrospection.
3541//===----------------------------------------------------------------------===//
3542
3543extern "C" {
3544unsigned clang_CXXMethod_isStatic(CXCursor C) {
3545 if (!clang_isDeclaration(C.kind))
3546 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003547
3548 CXXMethodDecl *Method = 0;
3549 Decl *D = cxcursor::getCursorDecl(C);
3550 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3551 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3552 else
3553 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3554 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003555}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003556
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003557} // end: extern "C"
3558
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003559//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003560// Attribute introspection.
3561//===----------------------------------------------------------------------===//
3562
3563extern "C" {
3564CXType clang_getIBOutletCollectionType(CXCursor C) {
3565 if (C.kind != CXCursor_IBOutletCollectionAttr)
3566 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3567
3568 IBOutletCollectionAttr *A =
3569 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3570
3571 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3572}
3573} // end: extern "C"
3574
3575//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003576// CXString Operations.
3577//===----------------------------------------------------------------------===//
3578
3579extern "C" {
3580const char *clang_getCString(CXString string) {
3581 return string.Spelling;
3582}
3583
3584void clang_disposeString(CXString string) {
3585 if (string.MustFreeString && string.Spelling)
3586 free((void*)string.Spelling);
3587}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003588
Ted Kremenekfb480492010-01-13 21:46:36 +00003589} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003590
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003591namespace clang { namespace cxstring {
3592CXString createCXString(const char *String, bool DupString){
3593 CXString Str;
3594 if (DupString) {
3595 Str.Spelling = strdup(String);
3596 Str.MustFreeString = 1;
3597 } else {
3598 Str.Spelling = String;
3599 Str.MustFreeString = 0;
3600 }
3601 return Str;
3602}
3603
3604CXString createCXString(llvm::StringRef String, bool DupString) {
3605 CXString Result;
3606 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3607 char *Spelling = (char *)malloc(String.size() + 1);
3608 memmove(Spelling, String.data(), String.size());
3609 Spelling[String.size()] = 0;
3610 Result.Spelling = Spelling;
3611 Result.MustFreeString = 1;
3612 } else {
3613 Result.Spelling = String.data();
3614 Result.MustFreeString = 0;
3615 }
3616 return Result;
3617}
3618}}
3619
Ted Kremenek04bb7162010-01-22 22:44:15 +00003620//===----------------------------------------------------------------------===//
3621// Misc. utility functions.
3622//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003623
Ted Kremenek04bb7162010-01-22 22:44:15 +00003624extern "C" {
3625
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003626CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003627 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003628}
3629
3630} // end: extern "C"