blob: 919962cfdeb5b753d29d33cefa3178ddefc57bea [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 Gregorfe72e9c2010-08-31 17:01:39 +0000293 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000294 bool VisitEnumConstantDecl(EnumConstantDecl *D);
295 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
296 bool VisitFunctionDecl(FunctionDecl *ND);
297 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000298 bool VisitVarDecl(VarDecl *);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000299 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000300 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000301 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
302 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
303 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
304 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000305 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000306 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
307 bool VisitObjCImplDecl(ObjCImplDecl *D);
308 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
309 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
310 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
311 // etc.
312 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
313 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
314 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000315 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000316 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000317
Douglas Gregor01829d32010-08-31 14:41:23 +0000318 // Name visitor
319 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
320
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000321 // Template visitors
322 bool VisitTemplateParameters(const TemplateParameterList *Params);
323 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
324
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000325 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000326 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000327 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000328 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000329 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
330 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000331 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000332 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000333 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000334 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
335 bool VisitPointerTypeLoc(PointerTypeLoc TL);
336 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
337 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
338 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
339 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000340 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000341 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000342 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000343 // FIXME: Implement visitors here when the unimplemented TypeLocs get
344 // implemented
345 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
346 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000347
Douglas Gregora59e3902010-01-21 23:27:09 +0000348 // Statement visitors
349 bool VisitStmt(Stmt *S);
350 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000351 // FIXME: LabelStmt label?
352 bool VisitIfStmt(IfStmt *S);
353 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000354 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000355 bool VisitWhileStmt(WhileStmt *S);
356 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000357// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000358
Douglas Gregor336fd812010-01-23 00:40:08 +0000359 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000360 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
361 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000362 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000363 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000364 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000365 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000366 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000367 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000368 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000369 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000370 // FIXME: AddrLabelExpr (once we have cursors for labels)
371 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
372 bool VisitVAArgExpr(VAArgExpr *E);
373 // FIXME: InitListExpr (for the designators)
374 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000375};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000376
Ted Kremenekab188932010-01-05 19:32:54 +0000377} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000378
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000379static SourceRange getRawCursorExtent(CXCursor C);
380
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000381RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000382 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
383}
384
Douglas Gregorb1373d02010-01-20 20:59:29 +0000385/// \brief Visit the given cursor and, if requested by the visitor,
386/// its children.
387///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000388/// \param Cursor the cursor to visit.
389///
390/// \param CheckRegionOfInterest if true, then the caller already checked that
391/// this cursor is within the region of interest.
392///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000393/// \returns true if the visitation should be aborted, false if it
394/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000395bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396 if (clang_isInvalid(Cursor.kind))
397 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000398
Douglas Gregorb1373d02010-01-20 20:59:29 +0000399 if (clang_isDeclaration(Cursor.kind)) {
400 Decl *D = getCursorDecl(Cursor);
401 assert(D && "Invalid declaration cursor");
402 if (D->getPCHLevel() > MaxPCHLevel)
403 return false;
404
405 if (D->isImplicit())
406 return false;
407 }
408
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000409 // If we have a range of interest, and this cursor doesn't intersect with it,
410 // we're done.
411 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000412 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000413 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000414 return false;
415 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000416
Douglas Gregorb1373d02010-01-20 20:59:29 +0000417 switch (Visitor(Cursor, Parent, ClientData)) {
418 case CXChildVisit_Break:
419 return true;
420
421 case CXChildVisit_Continue:
422 return false;
423
424 case CXChildVisit_Recurse:
425 return VisitChildren(Cursor);
426 }
427
Douglas Gregorfd643772010-01-25 16:45:46 +0000428 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000429}
430
Douglas Gregor788f5a12010-03-20 00:41:21 +0000431std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
432CursorVisitor::getPreprocessedEntities() {
433 PreprocessingRecord &PPRec
434 = *TU->getPreprocessor().getPreprocessingRecord();
435
436 bool OnlyLocalDecls
437 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
438
439 // There is no region of interest; we have to walk everything.
440 if (RegionOfInterest.isInvalid())
441 return std::make_pair(PPRec.begin(OnlyLocalDecls),
442 PPRec.end(OnlyLocalDecls));
443
444 // Find the file in which the region of interest lands.
445 SourceManager &SM = TU->getSourceManager();
446 std::pair<FileID, unsigned> Begin
447 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
448 std::pair<FileID, unsigned> End
449 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
450
451 // The region of interest spans files; we have to walk everything.
452 if (Begin.first != End.first)
453 return std::make_pair(PPRec.begin(OnlyLocalDecls),
454 PPRec.end(OnlyLocalDecls));
455
456 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
457 = TU->getPreprocessedEntitiesByFile();
458 if (ByFileMap.empty()) {
459 // Build the mapping from files to sets of preprocessed entities.
460 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
461 EEnd = PPRec.end(OnlyLocalDecls);
462 E != EEnd; ++E) {
463 std::pair<FileID, unsigned> P
464 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
465 ByFileMap[P.first].push_back(*E);
466 }
467 }
468
469 return std::make_pair(ByFileMap[Begin.first].begin(),
470 ByFileMap[Begin.first].end());
471}
472
Douglas Gregorb1373d02010-01-20 20:59:29 +0000473/// \brief Visit the children of the given cursor.
474///
475/// \returns true if the visitation should be aborted, false if it
476/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000477bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000478 if (clang_isReference(Cursor.kind)) {
479 // By definition, references have no children.
480 return false;
481 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000482
483 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000484 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000485 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000486
Douglas Gregorb1373d02010-01-20 20:59:29 +0000487 if (clang_isDeclaration(Cursor.kind)) {
488 Decl *D = getCursorDecl(Cursor);
489 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000490 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000491 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000492
Douglas Gregora59e3902010-01-21 23:27:09 +0000493 if (clang_isStatement(Cursor.kind))
494 return Visit(getCursorStmt(Cursor));
495 if (clang_isExpression(Cursor.kind))
496 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000497
Douglas Gregorb1373d02010-01-20 20:59:29 +0000498 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000499 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000500 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
501 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000502 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
503 TLEnd = CXXUnit->top_level_end();
504 TL != TLEnd; ++TL) {
505 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000506 return true;
507 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 } else if (VisitDeclContext(
509 CXXUnit->getASTContext().getTranslationUnitDecl()))
510 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000511
Douglas Gregor0396f462010-03-19 05:22:59 +0000512 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000513 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000514 // FIXME: Once we have the ability to deserialize a preprocessing record,
515 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000516 PreprocessingRecord::iterator E, EEnd;
517 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000518 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
519 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
520 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000521
Douglas Gregor0396f462010-03-19 05:22:59 +0000522 continue;
523 }
524
525 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
526 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
527 return true;
528
529 continue;
530 }
531 }
532 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000533 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000534 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000535
Douglas Gregorb1373d02010-01-20 20:59:29 +0000536 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000537 return false;
538}
539
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000540bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000541 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
542 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000543
Ted Kremenek664cffd2010-07-22 11:30:19 +0000544 if (Stmt *Body = B->getBody())
545 return Visit(MakeCXCursor(Body, StmtParent, TU));
546
547 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000548}
549
Douglas Gregorb1373d02010-01-20 20:59:29 +0000550bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000551 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000552 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000553
Ted Kremenek23173d72010-05-18 21:09:07 +0000554 Decl *D = *I;
555 if (D->getLexicalDeclContext() != DC)
556 continue;
557
558 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000559
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000560 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000561 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000562 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000563 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000564
565 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000566 case RangeBefore:
567 // This declaration comes before the region of interest; skip it.
568 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000569
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000570 case RangeAfter:
571 // This declaration comes after the region of interest; we're done.
572 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000573
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000574 case RangeOverlap:
575 // This declaration overlaps the region of interest; visit it.
576 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000577 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000578 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000579
Daniel Dunbard52864b2010-02-14 10:02:57 +0000580 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000581 return true;
582 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000583
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000585}
586
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000587bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
588 llvm_unreachable("Translation units are visited directly by Visit()");
589 return false;
590}
591
592bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
593 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
594 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000595
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000596 return false;
597}
598
599bool CursorVisitor::VisitTagDecl(TagDecl *D) {
600 return VisitDeclContext(D);
601}
602
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000603bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
604 // FIXME: Visit default argument
605 return false;
606}
607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
609 if (Expr *Init = D->getInitExpr())
610 return Visit(MakeCXCursor(Init, StmtParent, TU));
611 return false;
612}
613
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000614bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
615 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
616 if (Visit(TSInfo->getTypeLoc()))
617 return true;
618
619 return false;
620}
621
Douglas Gregorb1373d02010-01-20 20:59:29 +0000622bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000623 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
624 // Visit the function declaration's syntactic components in the order
625 // written. This requires a bit of work.
626 TypeLoc TL = TSInfo->getTypeLoc();
627 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
628
629 // If we have a function declared directly (without the use of a typedef),
630 // visit just the return type. Otherwise, just visit the function's type
631 // now.
632 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
633 (!FTL && Visit(TL)))
634 return true;
635
636 // FIXME: Visit the nested-name-specifier, if present.
637
638 // Visit the declaration name.
639 if (VisitDeclarationNameInfo(ND->getNameInfo()))
640 return true;
641
642 // FIXME: Visit explicitly-specified template arguments!
643
644 // Visit the function parameters, if we have a function type.
645 if (FTL && VisitFunctionTypeLoc(*FTL, true))
646 return true;
647
648 // FIXME: Attributes?
649 }
650
Douglas Gregora59e3902010-01-21 23:27:09 +0000651 if (ND->isThisDeclarationADefinition() &&
652 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
653 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000654
Douglas Gregorb1373d02010-01-20 20:59:29 +0000655 return false;
656}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000657
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000658bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
659 if (VisitDeclaratorDecl(D))
660 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000661
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000662 if (Expr *BitWidth = D->getBitWidth())
663 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000664
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000665 return false;
666}
667
668bool CursorVisitor::VisitVarDecl(VarDecl *D) {
669 if (VisitDeclaratorDecl(D))
670 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000671
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000672 if (Expr *Init = D->getInit())
673 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000674
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000675 return false;
676}
677
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000678bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
679 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
680 // before visiting these template parameters.
681 if (VisitTemplateParameters(D->getTemplateParameters()))
682 return true;
683
684 return VisitFunctionDecl(D->getTemplatedDecl());
685}
686
Douglas Gregor39d6f072010-08-31 19:02:00 +0000687bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
688 // FIXME: Visit the "outer" template parameter lists on the TagDecl
689 // before visiting these template parameters.
690 if (VisitTemplateParameters(D->getTemplateParameters()))
691 return true;
692
693 return VisitCXXRecordDecl(D->getTemplatedDecl());
694}
695
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000696bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000697 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
698 if (Visit(TSInfo->getTypeLoc()))
699 return true;
700
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000701 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000702 PEnd = ND->param_end();
703 P != PEnd; ++P) {
704 if (Visit(MakeCXCursor(*P, TU)))
705 return true;
706 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000707
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000708 if (ND->isThisDeclarationADefinition() &&
709 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
710 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000711
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000712 return false;
713}
714
Douglas Gregora59e3902010-01-21 23:27:09 +0000715bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
716 return VisitDeclContext(D);
717}
718
Douglas Gregorb1373d02010-01-20 20:59:29 +0000719bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000720 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
721 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000722 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000723
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000724 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
725 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
726 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000727 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000728 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000729
Douglas Gregora59e3902010-01-21 23:27:09 +0000730 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000731}
732
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000733bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
734 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
735 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
736 E = PID->protocol_end(); I != E; ++I, ++PL)
737 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
738 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000739
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000740 return VisitObjCContainerDecl(PID);
741}
742
Ted Kremenek23173d72010-05-18 21:09:07 +0000743bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000744 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
745 return true;
746
Ted Kremenek23173d72010-05-18 21:09:07 +0000747 // FIXME: This implements a workaround with @property declarations also being
748 // installed in the DeclContext for the @interface. Eventually this code
749 // should be removed.
750 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
751 if (!CDecl || !CDecl->IsClassExtension())
752 return false;
753
754 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
755 if (!ID)
756 return false;
757
758 IdentifierInfo *PropertyId = PD->getIdentifier();
759 ObjCPropertyDecl *prevDecl =
760 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
761
762 if (!prevDecl)
763 return false;
764
765 // Visit synthesized methods since they will be skipped when visiting
766 // the @interface.
767 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
768 if (MD->isSynthesized())
769 if (Visit(MakeCXCursor(MD, TU)))
770 return true;
771
772 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
773 if (MD->isSynthesized())
774 if (Visit(MakeCXCursor(MD, TU)))
775 return true;
776
777 return false;
778}
779
Douglas Gregorb1373d02010-01-20 20:59:29 +0000780bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000781 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000782 if (D->getSuperClass() &&
783 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000785 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000786 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000787
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000788 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
789 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
790 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000791 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000792 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000793
Douglas Gregora59e3902010-01-21 23:27:09 +0000794 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000795}
796
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000797bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
798 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000799}
800
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000801bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000802 // 'ID' could be null when dealing with invalid code.
803 if (ObjCInterfaceDecl *ID = D->getClassInterface())
804 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
805 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000806
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000807 return VisitObjCImplDecl(D);
808}
809
810bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
811#if 0
812 // Issue callbacks for super class.
813 // FIXME: No source location information!
814 if (D->getSuperClass() &&
815 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000816 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000817 TU)))
818 return true;
819#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000820
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000821 return VisitObjCImplDecl(D);
822}
823
824bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
825 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
826 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
827 E = D->protocol_end();
828 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000829 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000830 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000831
832 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000833}
834
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000835bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
836 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
837 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
838 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000839
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000840 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000841}
842
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000843bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
844 return VisitDeclContext(D);
845}
846
Douglas Gregor01829d32010-08-31 14:41:23 +0000847bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
848 switch (Name.getName().getNameKind()) {
849 case clang::DeclarationName::Identifier:
850 case clang::DeclarationName::CXXLiteralOperatorName:
851 case clang::DeclarationName::CXXOperatorName:
852 case clang::DeclarationName::CXXUsingDirective:
853 return false;
854
855 case clang::DeclarationName::CXXConstructorName:
856 case clang::DeclarationName::CXXDestructorName:
857 case clang::DeclarationName::CXXConversionFunctionName:
858 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
859 return Visit(TSInfo->getTypeLoc());
860 return false;
861
862 case clang::DeclarationName::ObjCZeroArgSelector:
863 case clang::DeclarationName::ObjCOneArgSelector:
864 case clang::DeclarationName::ObjCMultiArgSelector:
865 // FIXME: Per-identifier location info?
866 return false;
867 }
868
869 return false;
870}
871
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000872bool CursorVisitor::VisitTemplateParameters(
873 const TemplateParameterList *Params) {
874 if (!Params)
875 return false;
876
877 for (TemplateParameterList::const_iterator P = Params->begin(),
878 PEnd = Params->end();
879 P != PEnd; ++P) {
880 if (Visit(MakeCXCursor(*P, TU)))
881 return true;
882 }
883
884 return false;
885}
886
887bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
888 switch (TAL.getArgument().getKind()) {
889 case TemplateArgument::Null:
890 case TemplateArgument::Integral:
891 return false;
892
893 case TemplateArgument::Pack:
894 // FIXME: Implement when variadic templates come along.
895 return false;
896
897 case TemplateArgument::Type:
898 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
899 return Visit(TSInfo->getTypeLoc());
900 return false;
901
902 case TemplateArgument::Declaration:
903 if (Expr *E = TAL.getSourceDeclExpression())
904 return Visit(MakeCXCursor(E, StmtParent, TU));
905 return false;
906
907 case TemplateArgument::Expression:
908 if (Expr *E = TAL.getSourceExpression())
909 return Visit(MakeCXCursor(E, StmtParent, TU));
910 return false;
911
912 case TemplateArgument::Template:
913 // FIXME: Visit template name.
914 return false;
915 }
916
917 return false;
918}
919
Ted Kremeneka0536d82010-05-07 01:04:29 +0000920bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
921 return VisitDeclContext(D);
922}
923
Douglas Gregor01829d32010-08-31 14:41:23 +0000924bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
925 return Visit(TL.getUnqualifiedLoc());
926}
927
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000928bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
929 ASTContext &Context = TU->getASTContext();
930
931 // Some builtin types (such as Objective-C's "id", "sel", and
932 // "Class") have associated declarations. Create cursors for those.
933 QualType VisitType;
934 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000935 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000936 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000937 case BuiltinType::Char_U:
938 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000939 case BuiltinType::Char16:
940 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000941 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000942 case BuiltinType::UInt:
943 case BuiltinType::ULong:
944 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000945 case BuiltinType::UInt128:
946 case BuiltinType::Char_S:
947 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000948 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000949 case BuiltinType::Short:
950 case BuiltinType::Int:
951 case BuiltinType::Long:
952 case BuiltinType::LongLong:
953 case BuiltinType::Int128:
954 case BuiltinType::Float:
955 case BuiltinType::Double:
956 case BuiltinType::LongDouble:
957 case BuiltinType::NullPtr:
958 case BuiltinType::Overload:
959 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000960 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000961
962 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000963 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000964
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000965 case BuiltinType::ObjCId:
966 VisitType = Context.getObjCIdType();
967 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000968
969 case BuiltinType::ObjCClass:
970 VisitType = Context.getObjCClassType();
971 break;
972
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000973 case BuiltinType::ObjCSel:
974 VisitType = Context.getObjCSelType();
975 break;
976 }
977
978 if (!VisitType.isNull()) {
979 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000980 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000981 TU));
982 }
983
984 return false;
985}
986
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000987bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
988 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
989}
990
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000991bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
992 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
993}
994
995bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
996 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
997}
998
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000999bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1000 // FIXME: We can't visit the template template parameter, but there's
1001 // no context information with which we can match up the depth/index in the
1002 // type to the appropriate
1003 return false;
1004}
1005
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001006bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1007 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1008 return true;
1009
John McCallc12c5bb2010-05-15 11:32:37 +00001010 return false;
1011}
1012
1013bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1014 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1015 return true;
1016
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001017 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1018 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1019 TU)))
1020 return true;
1021 }
1022
1023 return false;
1024}
1025
1026bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001027 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001028}
1029
1030bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1031 return Visit(TL.getPointeeLoc());
1032}
1033
1034bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1035 return Visit(TL.getPointeeLoc());
1036}
1037
1038bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1039 return Visit(TL.getPointeeLoc());
1040}
1041
1042bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001043 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001044}
1045
1046bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001048}
1049
Douglas Gregor01829d32010-08-31 14:41:23 +00001050bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1051 bool SkipResultType) {
1052 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001053 return true;
1054
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001055 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001056 if (Decl *D = TL.getArg(I))
1057 if (Visit(MakeCXCursor(D, TU)))
1058 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001059
1060 return false;
1061}
1062
1063bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1064 if (Visit(TL.getElementLoc()))
1065 return true;
1066
1067 if (Expr *Size = TL.getSizeExpr())
1068 return Visit(MakeCXCursor(Size, StmtParent, TU));
1069
1070 return false;
1071}
1072
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001073bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1074 TemplateSpecializationTypeLoc TL) {
1075 // FIXME: Visit the template name.
1076
1077 // Visit the template arguments.
1078 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1079 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1080 return true;
1081
1082 return false;
1083}
1084
Douglas Gregor2332c112010-01-21 20:48:56 +00001085bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1086 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1087}
1088
1089bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1090 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1091 return Visit(TSInfo->getTypeLoc());
1092
1093 return false;
1094}
1095
Douglas Gregora59e3902010-01-21 23:27:09 +00001096bool CursorVisitor::VisitStmt(Stmt *S) {
1097 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1098 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001099 if (Stmt *C = *Child)
1100 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1101 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001102 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001103
Douglas Gregora59e3902010-01-21 23:27:09 +00001104 return false;
1105}
1106
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001107bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1108 // Specially handle CaseStmts because they can be nested, e.g.:
1109 //
1110 // case 1:
1111 // case 2:
1112 //
1113 // In this case the second CaseStmt is the child of the first. Walking
1114 // these recursively can blow out the stack.
1115 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1116 while (true) {
1117 // Set the Parent field to Cursor, then back to its old value once we're
1118 // done.
1119 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1120
1121 if (Stmt *LHS = S->getLHS())
1122 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1123 return true;
1124 if (Stmt *RHS = S->getRHS())
1125 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1126 return true;
1127 if (Stmt *SubStmt = S->getSubStmt()) {
1128 if (!isa<CaseStmt>(SubStmt))
1129 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1130
1131 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1132 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1133 Cursor = MakeCXCursor(CS, StmtParent, TU);
1134 if (RegionOfInterest.isValid()) {
1135 SourceRange Range = CS->getSourceRange();
1136 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1137 return false;
1138 }
1139
1140 switch (Visitor(Cursor, Parent, ClientData)) {
1141 case CXChildVisit_Break: return true;
1142 case CXChildVisit_Continue: return false;
1143 case CXChildVisit_Recurse:
1144 // Perform tail-recursion manually.
1145 S = CS;
1146 continue;
1147 }
1148 }
1149 return false;
1150 }
1151}
1152
Douglas Gregora59e3902010-01-21 23:27:09 +00001153bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1154 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1155 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001156 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001157 return true;
1158 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001159
Douglas Gregora59e3902010-01-21 23:27:09 +00001160 return false;
1161}
1162
Douglas Gregorf5bab412010-01-22 01:00:11 +00001163bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1164 if (VarDecl *Var = S->getConditionVariable()) {
1165 if (Visit(MakeCXCursor(Var, TU)))
1166 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001167 }
1168
Douglas Gregor263b47b2010-01-25 16:12:32 +00001169 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1170 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001171 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1172 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001173 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1174 return true;
1175
1176 return false;
1177}
1178
1179bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1180 if (VarDecl *Var = S->getConditionVariable()) {
1181 if (Visit(MakeCXCursor(Var, TU)))
1182 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001183 }
1184
Douglas Gregor263b47b2010-01-25 16:12:32 +00001185 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1186 return true;
1187 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1188 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001189
Douglas Gregor263b47b2010-01-25 16:12:32 +00001190 return false;
1191}
1192
1193bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1194 if (VarDecl *Var = S->getConditionVariable()) {
1195 if (Visit(MakeCXCursor(Var, TU)))
1196 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001197 }
1198
Douglas Gregor263b47b2010-01-25 16:12:32 +00001199 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1200 return true;
1201 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001202 return true;
1203
Douglas Gregor263b47b2010-01-25 16:12:32 +00001204 return false;
1205}
1206
1207bool CursorVisitor::VisitForStmt(ForStmt *S) {
1208 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1209 return true;
1210 if (VarDecl *Var = S->getConditionVariable()) {
1211 if (Visit(MakeCXCursor(Var, TU)))
1212 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001213 }
1214
Douglas Gregor263b47b2010-01-25 16:12:32 +00001215 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1216 return true;
1217 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1218 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001219 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1220 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001221
Douglas Gregorf5bab412010-01-22 01:00:11 +00001222 return false;
1223}
1224
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001225bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1226 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1227 return true;
1228
1229 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1230 return true;
1231
1232 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1233 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1234 return true;
1235
1236 return false;
1237}
1238
Ted Kremenek3064ef92010-08-27 21:34:58 +00001239bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1240 if (D->isDefinition()) {
1241 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1242 E = D->bases_end(); I != E; ++I) {
1243 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1244 return true;
1245 }
1246 }
1247
1248 return VisitTagDecl(D);
1249}
1250
1251
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001252bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1253 return Visit(B->getBlockDecl());
1254}
1255
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001256bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1257 // FIXME: Visit fields as well?
1258 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1259 return true;
1260
1261 return VisitExpr(E);
1262}
1263
Douglas Gregor336fd812010-01-23 00:40:08 +00001264bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1265 if (E->isArgumentType()) {
1266 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1267 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001268
Douglas Gregor336fd812010-01-23 00:40:08 +00001269 return false;
1270 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001271
Douglas Gregor336fd812010-01-23 00:40:08 +00001272 return VisitExpr(E);
1273}
1274
1275bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1276 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1277 if (Visit(TSInfo->getTypeLoc()))
1278 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001279
Douglas Gregor336fd812010-01-23 00:40:08 +00001280 return VisitCastExpr(E);
1281}
1282
1283bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1284 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1285 if (Visit(TSInfo->getTypeLoc()))
1286 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001287
Douglas Gregor336fd812010-01-23 00:40:08 +00001288 return VisitExpr(E);
1289}
1290
Douglas Gregor648220e2010-08-10 15:02:34 +00001291bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1292 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1293 Visit(E->getArgTInfo2()->getTypeLoc());
1294}
1295
1296bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1297 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1298 return true;
1299
1300 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1301}
1302
Douglas Gregorc2350e52010-03-08 16:40:19 +00001303bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001304 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1305 if (Visit(TSInfo->getTypeLoc()))
1306 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001307
1308 return VisitExpr(E);
1309}
1310
Douglas Gregor81d34662010-04-20 15:39:42 +00001311bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1312 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1313}
1314
1315
Ted Kremenek09dfa372010-02-18 05:46:33 +00001316bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001317 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1318 i != e; ++i)
1319 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001320 return true;
1321
1322 return false;
1323}
1324
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001325extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001326CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1327 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001328 // We use crash recovery to make some of our APIs more reliable, implicitly
1329 // enable it.
1330 llvm::CrashRecoveryContext::Enable();
1331
Douglas Gregora030b7c2010-01-22 20:35:53 +00001332 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001333 if (excludeDeclarationsFromPCH)
1334 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001335 if (displayDiagnostics)
1336 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001337 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001338}
1339
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001340void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001341 if (CIdx)
1342 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001343 if (getenv("LIBCLANG_TIMING"))
1344 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001345}
1346
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001347void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001348 if (CIdx) {
1349 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1350 CXXIdx->setUseExternalASTGeneration(value);
1351 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001352}
1353
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001354CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001355 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001356 if (!CIdx)
1357 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001358
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001359 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001360
Douglas Gregor28019772010-04-05 23:52:57 +00001361 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001362 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001363 CXXIdx->getOnlyLocalDecls(),
1364 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001365}
1366
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001367unsigned clang_defaultEditingTranslationUnitOptions() {
1368 return CXTranslationUnit_PrecompiledPreamble;
1369}
1370
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001371CXTranslationUnit
1372clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1373 const char *source_filename,
1374 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001375 const char **command_line_args,
1376 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001377 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001378 return clang_parseTranslationUnit(CIdx, source_filename,
1379 command_line_args, num_command_line_args,
1380 unsaved_files, num_unsaved_files,
1381 CXTranslationUnit_DetailedPreprocessingRecord);
1382}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001383
1384struct ParseTranslationUnitInfo {
1385 CXIndex CIdx;
1386 const char *source_filename;
1387 const char **command_line_args;
1388 int num_command_line_args;
1389 struct CXUnsavedFile *unsaved_files;
1390 unsigned num_unsaved_files;
1391 unsigned options;
1392 CXTranslationUnit result;
1393};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001394static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001395 ParseTranslationUnitInfo *PTUI =
1396 static_cast<ParseTranslationUnitInfo*>(UserData);
1397 CXIndex CIdx = PTUI->CIdx;
1398 const char *source_filename = PTUI->source_filename;
1399 const char **command_line_args = PTUI->command_line_args;
1400 int num_command_line_args = PTUI->num_command_line_args;
1401 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1402 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1403 unsigned options = PTUI->options;
1404 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001405
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001406 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001407 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001408
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001409 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1410
Douglas Gregor44c181a2010-07-23 00:33:23 +00001411 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001412 bool CompleteTranslationUnit
1413 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001414 bool CacheCodeCompetionResults
1415 = options & CXTranslationUnit_CacheCompletionResults;
1416
Douglas Gregor5352ac02010-01-28 00:27:43 +00001417 // Configure the diagnostics.
1418 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001419 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1420 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001421
Douglas Gregor4db64a42010-01-23 00:14:00 +00001422 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1423 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001424 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001425 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001426 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001427 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1428 Buffer));
1429 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001430
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001431 if (!CXXIdx->getUseExternalASTGeneration()) {
1432 llvm::SmallVector<const char *, 16> Args;
1433
1434 // The 'source_filename' argument is optional. If the caller does not
1435 // specify it then it is assumed that the source file is specified
1436 // in the actual argument list.
1437 if (source_filename)
1438 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001439
1440 // Since the Clang C library is primarily used by batch tools dealing with
1441 // (often very broken) source code, where spell-checking can have a
1442 // significant negative impact on performance (particularly when
1443 // precompiled headers are involved), we disable it by default.
1444 // Note that we place this argument early in the list, so that it can be
1445 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001446 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001447
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001448 Args.insert(Args.end(), command_line_args,
1449 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001450
Douglas Gregor44c181a2010-07-23 00:33:23 +00001451 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001452 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1453 Args.push_back("-Xclang");
1454 Args.push_back("-detailed-preprocessing-record");
1455 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001456
Douglas Gregor5352ac02010-01-28 00:27:43 +00001457 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001458
Ted Kremenek29b72842010-01-07 22:49:05 +00001459#ifdef USE_CRASHTRACER
1460 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001461#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001462
Daniel Dunbar94220972009-12-05 02:17:18 +00001463 llvm::OwningPtr<ASTUnit> Unit(
1464 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001465 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001466 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001467 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001468 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001469 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001470 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001471 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001472 CompleteTranslationUnit,
1473 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001474
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001475 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001476 // Make sure to check that 'Unit' is non-NULL.
1477 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001478 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1479 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001480 D != DEnd; ++D) {
1481 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001482 CXString Msg = clang_formatDiagnostic(&Diag,
1483 clang_defaultDiagnosticDisplayOptions());
1484 fprintf(stderr, "%s\n", clang_getCString(Msg));
1485 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001486 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001487#ifdef LLVM_ON_WIN32
1488 // On Windows, force a flush, since there may be multiple copies of
1489 // stderr and stdout in the file system, all with different buffers
1490 // but writing to the same device.
1491 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001492#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001493 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001494 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001495
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001496 PTUI->result = Unit.take();
1497 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001498 }
1499
Ted Kremenek139ba862009-10-22 00:03:57 +00001500 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001501 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001502
Ted Kremenek139ba862009-10-22 00:03:57 +00001503 // First add the complete path to the 'clang' executable.
1504 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001505 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001506
Ted Kremenek139ba862009-10-22 00:03:57 +00001507 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001508 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001509
Ted Kremenek139ba862009-10-22 00:03:57 +00001510 // The 'source_filename' argument is optional. If the caller does not
1511 // specify it then it is assumed that the source file is specified
1512 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001513 if (source_filename)
1514 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001515
Steve Naroff37b5ac22009-10-15 20:50:09 +00001516 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001517 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001518 char astTmpFile[L_tmpnam];
1519 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001520
1521 // Since the Clang C library is primarily used by batch tools dealing with
1522 // (often very broken) source code, where spell-checking can have a
1523 // significant negative impact on performance (particularly when
1524 // precompiled headers are involved), we disable it by default.
1525 // Note that we place this argument early in the list, so that it can be
1526 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001527 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001528
Douglas Gregor4db64a42010-01-23 00:14:00 +00001529 // Remap any unsaved files to temporary files.
1530 std::vector<llvm::sys::Path> TemporaryFiles;
1531 std::vector<std::string> RemapArgs;
1532 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001533 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001534
Douglas Gregor4db64a42010-01-23 00:14:00 +00001535 // The pointers into the elements of RemapArgs are stable because we
1536 // won't be adding anything to RemapArgs after this point.
1537 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1538 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001539
Ted Kremenek139ba862009-10-22 00:03:57 +00001540 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1541 for (int i = 0; i < num_command_line_args; ++i)
1542 if (const char *arg = command_line_args[i]) {
1543 if (strcmp(arg, "-o") == 0) {
1544 ++i; // Also skip the matching argument.
1545 continue;
1546 }
1547 if (strcmp(arg, "-emit-ast") == 0 ||
1548 strcmp(arg, "-c") == 0 ||
1549 strcmp(arg, "-fsyntax-only") == 0) {
1550 continue;
1551 }
1552
1553 // Keep the argument.
1554 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001555 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001556
Douglas Gregord93256e2010-01-28 06:00:51 +00001557 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001558 char tmpFileResults[L_tmpnam];
1559 char *tmpResultsFileName = tmpnam(tmpFileResults);
1560 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001561 TemporaryFiles.push_back(DiagnosticsFile);
1562 argv.push_back("-fdiagnostics-binary");
1563
Douglas Gregor44c181a2010-07-23 00:33:23 +00001564 // Do we need the detailed preprocessing record?
1565 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1566 argv.push_back("-Xclang");
1567 argv.push_back("-detailed-preprocessing-record");
1568 }
1569
Ted Kremenek139ba862009-10-22 00:03:57 +00001570 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001571 argv.push_back(NULL);
1572
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001573 // Invoke 'clang'.
1574 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1575 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001576 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001577 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1578 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001579 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001580 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001581 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001582
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001583 if (!ErrMsg.empty()) {
1584 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001585 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001586 I != E; ++I) {
1587 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001588 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001589 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001590 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001591
Daniel Dunbar32141c82010-02-23 20:23:45 +00001592 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001593 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001594
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001595 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001596 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001597 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001598 RemappedFiles.size(),
1599 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001600 if (ATU) {
1601 LoadSerializedDiagnostics(DiagnosticsFile,
1602 num_unsaved_files, unsaved_files,
1603 ATU->getFileManager(),
1604 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001605 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001606 } else if (CXXIdx->getDisplayDiagnostics()) {
1607 // We failed to load the ASTUnit, but we can still deserialize the
1608 // diagnostics and emit them.
1609 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001610 Diagnostic Diag;
1611 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001612 // FIXME: Faked LangOpts!
1613 LangOptions LangOpts;
1614 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1615 LoadSerializedDiagnostics(DiagnosticsFile,
1616 num_unsaved_files, unsaved_files,
1617 FileMgr, SourceMgr, Diags);
1618 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1619 DEnd = Diags.end();
1620 D != DEnd; ++D) {
1621 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001622 CXString Msg = clang_formatDiagnostic(&Diag,
1623 clang_defaultDiagnosticDisplayOptions());
1624 fprintf(stderr, "%s\n", clang_getCString(Msg));
1625 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001626 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001627
1628#ifdef LLVM_ON_WIN32
1629 // On Windows, force a flush, since there may be multiple copies of
1630 // stderr and stdout in the file system, all with different buffers
1631 // but writing to the same device.
1632 fflush(stderr);
1633#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001634 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001635
Douglas Gregor313e26c2010-02-18 23:35:40 +00001636 if (ATU) {
1637 // Make the translation unit responsible for destroying all temporary files.
1638 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1639 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001640 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001641 } else {
1642 // Destroy all of the temporary files now; they can't be referenced any
1643 // longer.
1644 llvm::sys::Path(astTmpFile).eraseFromDisk();
1645 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1646 TemporaryFiles[i].eraseFromDisk();
1647 }
1648
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001649 PTUI->result = ATU;
1650}
1651CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1652 const char *source_filename,
1653 const char **command_line_args,
1654 int num_command_line_args,
1655 struct CXUnsavedFile *unsaved_files,
1656 unsigned num_unsaved_files,
1657 unsigned options) {
1658 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1659 num_command_line_args, unsaved_files, num_unsaved_files,
1660 options, 0 };
1661 llvm::CrashRecoveryContext CRC;
1662
1663 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001664 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1665 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1666 fprintf(stderr, " 'command_line_args' : [");
1667 for (int i = 0; i != num_command_line_args; ++i) {
1668 if (i)
1669 fprintf(stderr, ", ");
1670 fprintf(stderr, "'%s'", command_line_args[i]);
1671 }
1672 fprintf(stderr, "],\n");
1673 fprintf(stderr, " 'unsaved_files' : [");
1674 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1675 if (i)
1676 fprintf(stderr, ", ");
1677 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1678 unsaved_files[i].Length);
1679 }
1680 fprintf(stderr, "],\n");
1681 fprintf(stderr, " 'options' : %d,\n", options);
1682 fprintf(stderr, "}\n");
1683
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001684 return 0;
1685 }
1686
1687 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001688}
1689
Douglas Gregor19998442010-08-13 15:35:05 +00001690unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1691 return CXSaveTranslationUnit_None;
1692}
1693
1694int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1695 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001696 if (!TU)
1697 return 1;
1698
1699 return static_cast<ASTUnit *>(TU)->Save(FileName);
1700}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001701
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001702void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001703 if (CTUnit) {
1704 // If the translation unit has been marked as unsafe to free, just discard
1705 // it.
1706 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1707 return;
1708
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001709 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001710 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001711}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001712
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001713unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1714 return CXReparse_None;
1715}
1716
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001717struct ReparseTranslationUnitInfo {
1718 CXTranslationUnit TU;
1719 unsigned num_unsaved_files;
1720 struct CXUnsavedFile *unsaved_files;
1721 unsigned options;
1722 int result;
1723};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001724static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001725 ReparseTranslationUnitInfo *RTUI =
1726 static_cast<ReparseTranslationUnitInfo*>(UserData);
1727 CXTranslationUnit TU = RTUI->TU;
1728 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1729 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1730 unsigned options = RTUI->options;
1731 (void) options;
1732 RTUI->result = 1;
1733
Douglas Gregorabc563f2010-07-19 21:46:24 +00001734 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001735 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001736
1737 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1738 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1739 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1740 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001741 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001742 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1743 Buffer));
1744 }
1745
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001746 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1747 RemappedFiles.size()))
1748 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001749}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001750int clang_reparseTranslationUnit(CXTranslationUnit TU,
1751 unsigned num_unsaved_files,
1752 struct CXUnsavedFile *unsaved_files,
1753 unsigned options) {
1754 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1755 options, 0 };
1756 llvm::CrashRecoveryContext CRC;
1757
1758 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001759 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001760 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1761 return 1;
1762 }
1763
1764 return RTUI.result;
1765}
1766
Douglas Gregordf95a132010-08-09 20:45:32 +00001767
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001768CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001769 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001770 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001771
Steve Naroff77accc12009-09-03 18:19:54 +00001772 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001773 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001774}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001775
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001776CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001777 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001778 return Result;
1779}
1780
Ted Kremenekfb480492010-01-13 21:46:36 +00001781} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001782
Ted Kremenekfb480492010-01-13 21:46:36 +00001783//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001784// CXSourceLocation and CXSourceRange Operations.
1785//===----------------------------------------------------------------------===//
1786
Douglas Gregorb9790342010-01-22 21:44:22 +00001787extern "C" {
1788CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001789 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001790 return Result;
1791}
1792
1793unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001794 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1795 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1796 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001797}
1798
1799CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1800 CXFile file,
1801 unsigned line,
1802 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001803 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001804 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001805
Douglas Gregorb9790342010-01-22 21:44:22 +00001806 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1807 SourceLocation SLoc
1808 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001809 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001810 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001811
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001812 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001813}
1814
Douglas Gregor5352ac02010-01-28 00:27:43 +00001815CXSourceRange clang_getNullRange() {
1816 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1817 return Result;
1818}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001819
Douglas Gregor5352ac02010-01-28 00:27:43 +00001820CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1821 if (begin.ptr_data[0] != end.ptr_data[0] ||
1822 begin.ptr_data[1] != end.ptr_data[1])
1823 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001824
1825 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001826 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001827 return Result;
1828}
1829
Douglas Gregor46766dc2010-01-26 19:19:08 +00001830void clang_getInstantiationLocation(CXSourceLocation location,
1831 CXFile *file,
1832 unsigned *line,
1833 unsigned *column,
1834 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001835 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1836
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001837 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001838 if (file)
1839 *file = 0;
1840 if (line)
1841 *line = 0;
1842 if (column)
1843 *column = 0;
1844 if (offset)
1845 *offset = 0;
1846 return;
1847 }
1848
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001849 const SourceManager &SM =
1850 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001851 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001852
1853 if (file)
1854 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1855 if (line)
1856 *line = SM.getInstantiationLineNumber(InstLoc);
1857 if (column)
1858 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001859 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001860 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001861}
1862
Douglas Gregor1db19de2010-01-19 21:36:55 +00001863CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001864 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001865 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001866 return Result;
1867}
1868
1869CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001870 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001871 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001872 return Result;
1873}
1874
Douglas Gregorb9790342010-01-22 21:44:22 +00001875} // end: extern "C"
1876
Douglas Gregor1db19de2010-01-19 21:36:55 +00001877//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001878// CXFile Operations.
1879//===----------------------------------------------------------------------===//
1880
1881extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001882CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001883 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001884 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001885
Steve Naroff88145032009-10-27 14:35:18 +00001886 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001887 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001888}
1889
1890time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001891 if (!SFile)
1892 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001893
Steve Naroff88145032009-10-27 14:35:18 +00001894 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1895 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001896}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001897
Douglas Gregorb9790342010-01-22 21:44:22 +00001898CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1899 if (!tu)
1900 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001901
Douglas Gregorb9790342010-01-22 21:44:22 +00001902 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001903
Douglas Gregorb9790342010-01-22 21:44:22 +00001904 FileManager &FMgr = CXXUnit->getFileManager();
1905 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1906 return const_cast<FileEntry *>(File);
1907}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001908
Ted Kremenekfb480492010-01-13 21:46:36 +00001909} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001910
Ted Kremenekfb480492010-01-13 21:46:36 +00001911//===----------------------------------------------------------------------===//
1912// CXCursor Operations.
1913//===----------------------------------------------------------------------===//
1914
Ted Kremenekfb480492010-01-13 21:46:36 +00001915static Decl *getDeclFromExpr(Stmt *E) {
1916 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1917 return RefExpr->getDecl();
1918 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1919 return ME->getMemberDecl();
1920 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1921 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001922
Ted Kremenekfb480492010-01-13 21:46:36 +00001923 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1924 return getDeclFromExpr(CE->getCallee());
1925 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1926 return getDeclFromExpr(CE->getSubExpr());
1927 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1928 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001929
Ted Kremenekfb480492010-01-13 21:46:36 +00001930 return 0;
1931}
1932
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001933static SourceLocation getLocationFromExpr(Expr *E) {
1934 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1935 return /*FIXME:*/Msg->getLeftLoc();
1936 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1937 return DRE->getLocation();
1938 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1939 return Member->getMemberLoc();
1940 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1941 return Ivar->getLocation();
1942 return E->getLocStart();
1943}
1944
Ted Kremenekfb480492010-01-13 21:46:36 +00001945extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001946
1947unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001948 CXCursorVisitor visitor,
1949 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001950 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001951
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001952 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1953 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00001954 return CursorVis.VisitChildren(parent);
1955}
1956
Douglas Gregor78205d42010-01-20 21:45:58 +00001957static CXString getDeclSpelling(Decl *D) {
1958 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1959 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001960 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001961
Douglas Gregor78205d42010-01-20 21:45:58 +00001962 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001963 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001964
Douglas Gregor78205d42010-01-20 21:45:58 +00001965 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1966 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1967 // and returns different names. NamedDecl returns the class name and
1968 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001969 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001970
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001971 llvm::SmallString<1024> S;
1972 llvm::raw_svector_ostream os(S);
1973 ND->printName(os);
1974
1975 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001976}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001977
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001978CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001979 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001980 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001981
Steve Narofff334b4e2009-09-02 18:26:48 +00001982 if (clang_isReference(C.kind)) {
1983 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001984 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001985 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001986 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001987 }
1988 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001989 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001990 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001991 }
1992 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001993 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001994 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001995 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001996 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00001997 case CXCursor_CXXBaseSpecifier: {
1998 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
1999 return createCXString(B->getType().getAsString());
2000 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002001 case CXCursor_TypeRef: {
2002 TypeDecl *Type = getCursorTypeRef(C).first;
2003 assert(Type && "Missing type decl");
2004
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002005 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2006 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002007 }
2008
Daniel Dunbaracca7252009-11-30 20:42:49 +00002009 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002010 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002011 }
2012 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002013
2014 if (clang_isExpression(C.kind)) {
2015 Decl *D = getDeclFromExpr(getCursorExpr(C));
2016 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002017 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002018 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002019 }
2020
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002021 if (C.kind == CXCursor_MacroInstantiation)
2022 return createCXString(getCursorMacroInstantiation(C)->getName()
2023 ->getNameStart());
2024
Douglas Gregor572feb22010-03-18 18:04:21 +00002025 if (C.kind == CXCursor_MacroDefinition)
2026 return createCXString(getCursorMacroDefinition(C)->getName()
2027 ->getNameStart());
2028
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002029 if (clang_isDeclaration(C.kind))
2030 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002031
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002032 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002033}
2034
Ted Kremeneke68fff62010-02-17 00:41:32 +00002035CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002036 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002037 case CXCursor_FunctionDecl:
2038 return createCXString("FunctionDecl");
2039 case CXCursor_TypedefDecl:
2040 return createCXString("TypedefDecl");
2041 case CXCursor_EnumDecl:
2042 return createCXString("EnumDecl");
2043 case CXCursor_EnumConstantDecl:
2044 return createCXString("EnumConstantDecl");
2045 case CXCursor_StructDecl:
2046 return createCXString("StructDecl");
2047 case CXCursor_UnionDecl:
2048 return createCXString("UnionDecl");
2049 case CXCursor_ClassDecl:
2050 return createCXString("ClassDecl");
2051 case CXCursor_FieldDecl:
2052 return createCXString("FieldDecl");
2053 case CXCursor_VarDecl:
2054 return createCXString("VarDecl");
2055 case CXCursor_ParmDecl:
2056 return createCXString("ParmDecl");
2057 case CXCursor_ObjCInterfaceDecl:
2058 return createCXString("ObjCInterfaceDecl");
2059 case CXCursor_ObjCCategoryDecl:
2060 return createCXString("ObjCCategoryDecl");
2061 case CXCursor_ObjCProtocolDecl:
2062 return createCXString("ObjCProtocolDecl");
2063 case CXCursor_ObjCPropertyDecl:
2064 return createCXString("ObjCPropertyDecl");
2065 case CXCursor_ObjCIvarDecl:
2066 return createCXString("ObjCIvarDecl");
2067 case CXCursor_ObjCInstanceMethodDecl:
2068 return createCXString("ObjCInstanceMethodDecl");
2069 case CXCursor_ObjCClassMethodDecl:
2070 return createCXString("ObjCClassMethodDecl");
2071 case CXCursor_ObjCImplementationDecl:
2072 return createCXString("ObjCImplementationDecl");
2073 case CXCursor_ObjCCategoryImplDecl:
2074 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002075 case CXCursor_CXXMethod:
2076 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002077 case CXCursor_UnexposedDecl:
2078 return createCXString("UnexposedDecl");
2079 case CXCursor_ObjCSuperClassRef:
2080 return createCXString("ObjCSuperClassRef");
2081 case CXCursor_ObjCProtocolRef:
2082 return createCXString("ObjCProtocolRef");
2083 case CXCursor_ObjCClassRef:
2084 return createCXString("ObjCClassRef");
2085 case CXCursor_TypeRef:
2086 return createCXString("TypeRef");
2087 case CXCursor_UnexposedExpr:
2088 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002089 case CXCursor_BlockExpr:
2090 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002091 case CXCursor_DeclRefExpr:
2092 return createCXString("DeclRefExpr");
2093 case CXCursor_MemberRefExpr:
2094 return createCXString("MemberRefExpr");
2095 case CXCursor_CallExpr:
2096 return createCXString("CallExpr");
2097 case CXCursor_ObjCMessageExpr:
2098 return createCXString("ObjCMessageExpr");
2099 case CXCursor_UnexposedStmt:
2100 return createCXString("UnexposedStmt");
2101 case CXCursor_InvalidFile:
2102 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002103 case CXCursor_InvalidCode:
2104 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002105 case CXCursor_NoDeclFound:
2106 return createCXString("NoDeclFound");
2107 case CXCursor_NotImplemented:
2108 return createCXString("NotImplemented");
2109 case CXCursor_TranslationUnit:
2110 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002111 case CXCursor_UnexposedAttr:
2112 return createCXString("UnexposedAttr");
2113 case CXCursor_IBActionAttr:
2114 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002115 case CXCursor_IBOutletAttr:
2116 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002117 case CXCursor_IBOutletCollectionAttr:
2118 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002119 case CXCursor_PreprocessingDirective:
2120 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002121 case CXCursor_MacroDefinition:
2122 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002123 case CXCursor_MacroInstantiation:
2124 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002125 case CXCursor_Namespace:
2126 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002127 case CXCursor_LinkageSpec:
2128 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002129 case CXCursor_CXXBaseSpecifier:
2130 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002131 case CXCursor_Constructor:
2132 return createCXString("CXXConstructor");
2133 case CXCursor_Destructor:
2134 return createCXString("CXXDestructor");
2135 case CXCursor_ConversionFunction:
2136 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002137 case CXCursor_TemplateTypeParameter:
2138 return createCXString("TemplateTypeParameter");
2139 case CXCursor_NonTypeTemplateParameter:
2140 return createCXString("NonTypeTemplateParameter");
2141 case CXCursor_TemplateTemplateParameter:
2142 return createCXString("TemplateTemplateParameter");
2143 case CXCursor_FunctionTemplate:
2144 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002145 case CXCursor_ClassTemplate:
2146 return createCXString("ClassTemplate");
Steve Naroff89922f82009-08-31 00:59:03 +00002147 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002148
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002149 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002150 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002151}
Steve Naroff89922f82009-08-31 00:59:03 +00002152
Ted Kremeneke68fff62010-02-17 00:41:32 +00002153enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2154 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002155 CXClientData client_data) {
2156 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2157 *BestCursor = cursor;
2158 return CXChildVisit_Recurse;
2159}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002160
Douglas Gregorb9790342010-01-22 21:44:22 +00002161CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2162 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002163 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002164
Douglas Gregorb9790342010-01-22 21:44:22 +00002165 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002166 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2167
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002168 // Translate the given source location to make it point at the beginning of
2169 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002170 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002171
2172 // Guard against an invalid SourceLocation, or we may assert in one
2173 // of the following calls.
2174 if (SLoc.isInvalid())
2175 return clang_getNullCursor();
2176
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002177 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2178 CXXUnit->getASTContext().getLangOptions());
2179
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002180 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2181 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002182 // FIXME: Would be great to have a "hint" cursor, then walk from that
2183 // hint cursor upward until we find a cursor whose source range encloses
2184 // the region of interest, rather than starting from the translation unit.
2185 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002186 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002187 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002188 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002189 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002190 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002191}
2192
Ted Kremenek73885552009-11-17 19:28:59 +00002193CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002194 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002195}
2196
2197unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002198 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002199}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002200
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002201unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002202 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2203}
2204
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002205unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002206 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2207}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002208
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002209unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002210 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2211}
2212
Douglas Gregor97b98722010-01-19 23:20:36 +00002213unsigned clang_isExpression(enum CXCursorKind K) {
2214 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2215}
2216
2217unsigned clang_isStatement(enum CXCursorKind K) {
2218 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2219}
2220
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002221unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2222 return K == CXCursor_TranslationUnit;
2223}
2224
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002225unsigned clang_isPreprocessing(enum CXCursorKind K) {
2226 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2227}
2228
Ted Kremenekad6eff62010-03-08 21:17:29 +00002229unsigned clang_isUnexposed(enum CXCursorKind K) {
2230 switch (K) {
2231 case CXCursor_UnexposedDecl:
2232 case CXCursor_UnexposedExpr:
2233 case CXCursor_UnexposedStmt:
2234 case CXCursor_UnexposedAttr:
2235 return true;
2236 default:
2237 return false;
2238 }
2239}
2240
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002241CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002242 return C.kind;
2243}
2244
Douglas Gregor98258af2010-01-18 22:46:11 +00002245CXSourceLocation clang_getCursorLocation(CXCursor C) {
2246 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002247 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002248 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002249 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2250 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002251 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002252 }
2253
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002254 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002255 std::pair<ObjCProtocolDecl *, SourceLocation> P
2256 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002257 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002258 }
2259
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002260 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002261 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2262 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002263 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002264 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002265
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002266 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002267 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002268 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002269 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002270
2271 case CXCursor_CXXBaseSpecifier: {
2272 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2273 return clang_getNullLocation();
2274 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002275
Douglas Gregorf46034a2010-01-18 23:41:10 +00002276 default:
2277 // FIXME: Need a way to enumerate all non-reference cases.
2278 llvm_unreachable("Missed a reference kind");
2279 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002280 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002281
2282 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002283 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002284 getLocationFromExpr(getCursorExpr(C)));
2285
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002286 if (C.kind == CXCursor_PreprocessingDirective) {
2287 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2288 return cxloc::translateSourceLocation(getCursorContext(C), L);
2289 }
Douglas Gregor48072312010-03-18 15:23:44 +00002290
2291 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002292 SourceLocation L
2293 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002294 return cxloc::translateSourceLocation(getCursorContext(C), L);
2295 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002296
2297 if (C.kind == CXCursor_MacroDefinition) {
2298 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2299 return cxloc::translateSourceLocation(getCursorContext(C), L);
2300 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002301
Ted Kremenek9a700d22010-05-12 06:16:13 +00002302 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002303 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002304
Douglas Gregorf46034a2010-01-18 23:41:10 +00002305 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002306 SourceLocation Loc = D->getLocation();
2307 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2308 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002309 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002310}
Douglas Gregora7bde202010-01-19 00:34:46 +00002311
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002312} // end extern "C"
2313
2314static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002315 if (clang_isReference(C.kind)) {
2316 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002317 case CXCursor_ObjCSuperClassRef:
2318 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002319
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002320 case CXCursor_ObjCProtocolRef:
2321 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002322
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002323 case CXCursor_ObjCClassRef:
2324 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002325
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002326 case CXCursor_TypeRef:
2327 return getCursorTypeRef(C).second;
Ted Kremenek3064ef92010-08-27 21:34:58 +00002328
2329 case CXCursor_CXXBaseSpecifier:
2330 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2331 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002332
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002333 default:
2334 // FIXME: Need a way to enumerate all non-reference cases.
2335 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002336 }
2337 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002338
2339 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002340 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002341
2342 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002343 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002344
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002345 if (C.kind == CXCursor_PreprocessingDirective)
2346 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002347
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002348 if (C.kind == CXCursor_MacroInstantiation)
2349 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002350
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002351 if (C.kind == CXCursor_MacroDefinition)
2352 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002353
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002354 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2355 return getCursorDecl(C)->getSourceRange();
2356
2357 return SourceRange();
2358}
2359
2360extern "C" {
2361
2362CXSourceRange clang_getCursorExtent(CXCursor C) {
2363 SourceRange R = getRawCursorExtent(C);
2364 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002365 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002366
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002367 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002368}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002369
2370CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002371 if (clang_isInvalid(C.kind))
2372 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002373
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002374 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002375 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002376 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002377
Douglas Gregor97b98722010-01-19 23:20:36 +00002378 if (clang_isExpression(C.kind)) {
2379 Decl *D = getDeclFromExpr(getCursorExpr(C));
2380 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002381 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002382 return clang_getNullCursor();
2383 }
2384
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002385 if (C.kind == CXCursor_MacroInstantiation) {
2386 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2387 return MakeMacroDefinitionCursor(Def, CXXUnit);
2388 }
2389
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002390 if (!clang_isReference(C.kind))
2391 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002392
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002393 switch (C.kind) {
2394 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002395 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002396
2397 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002398 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002399
2400 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002401 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002402
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002403 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002404 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenek3064ef92010-08-27 21:34:58 +00002405
2406 case CXCursor_CXXBaseSpecifier: {
2407 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2408 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2409 CXXUnit));
2410 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002411
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002412 default:
2413 // We would prefer to enumerate all non-reference cursor kinds here.
2414 llvm_unreachable("Unhandled reference cursor kind");
2415 break;
2416 }
2417 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002418
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002419 return clang_getNullCursor();
2420}
2421
Douglas Gregorb6998662010-01-19 19:34:47 +00002422CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002423 if (clang_isInvalid(C.kind))
2424 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002425
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002426 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002427
Douglas Gregorb6998662010-01-19 19:34:47 +00002428 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002429 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002430 C = clang_getCursorReferenced(C);
2431 WasReference = true;
2432 }
2433
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002434 if (C.kind == CXCursor_MacroInstantiation)
2435 return clang_getCursorReferenced(C);
2436
Douglas Gregorb6998662010-01-19 19:34:47 +00002437 if (!clang_isDeclaration(C.kind))
2438 return clang_getNullCursor();
2439
2440 Decl *D = getCursorDecl(C);
2441 if (!D)
2442 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002443
Douglas Gregorb6998662010-01-19 19:34:47 +00002444 switch (D->getKind()) {
2445 // Declaration kinds that don't really separate the notions of
2446 // declaration and definition.
2447 case Decl::Namespace:
2448 case Decl::Typedef:
2449 case Decl::TemplateTypeParm:
2450 case Decl::EnumConstant:
2451 case Decl::Field:
2452 case Decl::ObjCIvar:
2453 case Decl::ObjCAtDefsField:
2454 case Decl::ImplicitParam:
2455 case Decl::ParmVar:
2456 case Decl::NonTypeTemplateParm:
2457 case Decl::TemplateTemplateParm:
2458 case Decl::ObjCCategoryImpl:
2459 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002460 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002461 case Decl::LinkageSpec:
2462 case Decl::ObjCPropertyImpl:
2463 case Decl::FileScopeAsm:
2464 case Decl::StaticAssert:
2465 case Decl::Block:
2466 return C;
2467
2468 // Declaration kinds that don't make any sense here, but are
2469 // nonetheless harmless.
2470 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002471 break;
2472
2473 // Declaration kinds for which the definition is not resolvable.
2474 case Decl::UnresolvedUsingTypename:
2475 case Decl::UnresolvedUsingValue:
2476 break;
2477
2478 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002479 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2480 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002481
2482 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002483 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002484
2485 case Decl::Enum:
2486 case Decl::Record:
2487 case Decl::CXXRecord:
2488 case Decl::ClassTemplateSpecialization:
2489 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002490 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002491 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002492 return clang_getNullCursor();
2493
2494 case Decl::Function:
2495 case Decl::CXXMethod:
2496 case Decl::CXXConstructor:
2497 case Decl::CXXDestructor:
2498 case Decl::CXXConversion: {
2499 const FunctionDecl *Def = 0;
2500 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002501 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002502 return clang_getNullCursor();
2503 }
2504
2505 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002506 // Ask the variable if it has a definition.
2507 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2508 return MakeCXCursor(Def, CXXUnit);
2509 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002510 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002511
Douglas Gregorb6998662010-01-19 19:34:47 +00002512 case Decl::FunctionTemplate: {
2513 const FunctionDecl *Def = 0;
2514 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002515 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002516 return clang_getNullCursor();
2517 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002518
Douglas Gregorb6998662010-01-19 19:34:47 +00002519 case Decl::ClassTemplate: {
2520 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002521 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002522 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002523 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002524 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002525 return clang_getNullCursor();
2526 }
2527
2528 case Decl::Using: {
2529 UsingDecl *Using = cast<UsingDecl>(D);
2530 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002531 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2532 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002533 S != SEnd; ++S) {
2534 if (Def != clang_getNullCursor()) {
2535 // FIXME: We have no way to return multiple results.
2536 return clang_getNullCursor();
2537 }
2538
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002539 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002540 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002541 }
2542
2543 return Def;
2544 }
2545
2546 case Decl::UsingShadow:
2547 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002548 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002549 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002550
2551 case Decl::ObjCMethod: {
2552 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2553 if (Method->isThisDeclarationADefinition())
2554 return C;
2555
2556 // Dig out the method definition in the associated
2557 // @implementation, if we have it.
2558 // FIXME: The ASTs should make finding the definition easier.
2559 if (ObjCInterfaceDecl *Class
2560 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2561 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2562 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2563 Method->isInstanceMethod()))
2564 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002565 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002566
2567 return clang_getNullCursor();
2568 }
2569
2570 case Decl::ObjCCategory:
2571 if (ObjCCategoryImplDecl *Impl
2572 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002573 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002574 return clang_getNullCursor();
2575
2576 case Decl::ObjCProtocol:
2577 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2578 return C;
2579 return clang_getNullCursor();
2580
2581 case Decl::ObjCInterface:
2582 // There are two notions of a "definition" for an Objective-C
2583 // class: the interface and its implementation. When we resolved a
2584 // reference to an Objective-C class, produce the @interface as
2585 // the definition; when we were provided with the interface,
2586 // produce the @implementation as the definition.
2587 if (WasReference) {
2588 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2589 return C;
2590 } else if (ObjCImplementationDecl *Impl
2591 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002592 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002593 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002594
Douglas Gregorb6998662010-01-19 19:34:47 +00002595 case Decl::ObjCProperty:
2596 // FIXME: We don't really know where to find the
2597 // ObjCPropertyImplDecls that implement this property.
2598 return clang_getNullCursor();
2599
2600 case Decl::ObjCCompatibleAlias:
2601 if (ObjCInterfaceDecl *Class
2602 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2603 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002604 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002605
Douglas Gregorb6998662010-01-19 19:34:47 +00002606 return clang_getNullCursor();
2607
2608 case Decl::ObjCForwardProtocol: {
2609 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2610 if (Forward->protocol_size() == 1)
2611 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002612 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002613 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002614
2615 // FIXME: Cannot return multiple definitions.
2616 return clang_getNullCursor();
2617 }
2618
2619 case Decl::ObjCClass: {
2620 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2621 if (Class->size() == 1) {
2622 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2623 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002624 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002625 return clang_getNullCursor();
2626 }
2627
2628 // FIXME: Cannot return multiple definitions.
2629 return clang_getNullCursor();
2630 }
2631
2632 case Decl::Friend:
2633 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002634 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002635 return clang_getNullCursor();
2636
2637 case Decl::FriendTemplate:
2638 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002639 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002640 return clang_getNullCursor();
2641 }
2642
2643 return clang_getNullCursor();
2644}
2645
2646unsigned clang_isCursorDefinition(CXCursor C) {
2647 if (!clang_isDeclaration(C.kind))
2648 return 0;
2649
2650 return clang_getCursorDefinition(C) == C;
2651}
2652
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002653void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002654 const char **startBuf,
2655 const char **endBuf,
2656 unsigned *startLine,
2657 unsigned *startColumn,
2658 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002659 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002660 assert(getCursorDecl(C) && "CXCursor has null decl");
2661 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002662 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2663 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002664
Steve Naroff4ade6d62009-09-23 17:52:52 +00002665 SourceManager &SM = FD->getASTContext().getSourceManager();
2666 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2667 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2668 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2669 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2670 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2671 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2672}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002673
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002674void clang_enableStackTraces(void) {
2675 llvm::sys::PrintStackTraceOnErrorSignal();
2676}
2677
Ted Kremenekfb480492010-01-13 21:46:36 +00002678} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002679
Ted Kremenekfb480492010-01-13 21:46:36 +00002680//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002681// Token-based Operations.
2682//===----------------------------------------------------------------------===//
2683
2684/* CXToken layout:
2685 * int_data[0]: a CXTokenKind
2686 * int_data[1]: starting token location
2687 * int_data[2]: token length
2688 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002689 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002690 * otherwise unused.
2691 */
2692extern "C" {
2693
2694CXTokenKind clang_getTokenKind(CXToken CXTok) {
2695 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2696}
2697
2698CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2699 switch (clang_getTokenKind(CXTok)) {
2700 case CXToken_Identifier:
2701 case CXToken_Keyword:
2702 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002703 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2704 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002705
2706 case CXToken_Literal: {
2707 // We have stashed the starting pointer in the ptr_data field. Use it.
2708 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002709 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002710 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002711
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002712 case CXToken_Punctuation:
2713 case CXToken_Comment:
2714 break;
2715 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002716
2717 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002718 // deconstructing the source location.
2719 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2720 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002721 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002722
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002723 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2724 std::pair<FileID, unsigned> LocInfo
2725 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002726 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002727 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002728 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2729 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002730 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002731
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002732 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002733}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002734
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002735CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2736 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2737 if (!CXXUnit)
2738 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002739
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002740 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2741 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2742}
2743
2744CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2745 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002746 if (!CXXUnit)
2747 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002748
2749 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002750 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2751}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002752
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002753void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2754 CXToken **Tokens, unsigned *NumTokens) {
2755 if (Tokens)
2756 *Tokens = 0;
2757 if (NumTokens)
2758 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002759
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002760 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2761 if (!CXXUnit || !Tokens || !NumTokens)
2762 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002763
Douglas Gregorbdf60622010-03-05 21:16:25 +00002764 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2765
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002766 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002767 if (R.isInvalid())
2768 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002769
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002770 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2771 std::pair<FileID, unsigned> BeginLocInfo
2772 = SourceMgr.getDecomposedLoc(R.getBegin());
2773 std::pair<FileID, unsigned> EndLocInfo
2774 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002775
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002776 // Cannot tokenize across files.
2777 if (BeginLocInfo.first != EndLocInfo.first)
2778 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002779
2780 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002781 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002782 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002783 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002784 if (Invalid)
2785 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002786
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002787 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2788 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002789 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002790 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002791
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002792 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002793 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002794 llvm::SmallVector<CXToken, 32> CXTokens;
2795 Token Tok;
2796 do {
2797 // Lex the next token
2798 Lex.LexFromRawLexer(Tok);
2799 if (Tok.is(tok::eof))
2800 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002801
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002802 // Initialize the CXToken.
2803 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002804
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002805 // - Common fields
2806 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2807 CXTok.int_data[2] = Tok.getLength();
2808 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002809
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002810 // - Kind-specific fields
2811 if (Tok.isLiteral()) {
2812 CXTok.int_data[0] = CXToken_Literal;
2813 CXTok.ptr_data = (void *)Tok.getLiteralData();
2814 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002815 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002816 std::pair<FileID, unsigned> LocInfo
2817 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002818 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002819 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002820 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2821 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002822 return;
2823
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002824 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002825 IdentifierInfo *II
2826 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002827
2828 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2829 CXTok.int_data[0] = CXToken_Keyword;
2830 }
2831 else {
2832 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2833 CXToken_Identifier
2834 : CXToken_Keyword;
2835 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002836 CXTok.ptr_data = II;
2837 } else if (Tok.is(tok::comment)) {
2838 CXTok.int_data[0] = CXToken_Comment;
2839 CXTok.ptr_data = 0;
2840 } else {
2841 CXTok.int_data[0] = CXToken_Punctuation;
2842 CXTok.ptr_data = 0;
2843 }
2844 CXTokens.push_back(CXTok);
2845 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002846
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002847 if (CXTokens.empty())
2848 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002849
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002850 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2851 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2852 *NumTokens = CXTokens.size();
2853}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002854
Ted Kremenek6db61092010-05-05 00:55:15 +00002855void clang_disposeTokens(CXTranslationUnit TU,
2856 CXToken *Tokens, unsigned NumTokens) {
2857 free(Tokens);
2858}
2859
2860} // end: extern "C"
2861
2862//===----------------------------------------------------------------------===//
2863// Token annotation APIs.
2864//===----------------------------------------------------------------------===//
2865
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002866typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002867static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2868 CXCursor parent,
2869 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002870namespace {
2871class AnnotateTokensWorker {
2872 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002873 CXToken *Tokens;
2874 CXCursor *Cursors;
2875 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002876 unsigned TokIdx;
2877 CursorVisitor AnnotateVis;
2878 SourceManager &SrcMgr;
2879
2880 bool MoreTokens() const { return TokIdx < NumTokens; }
2881 unsigned NextToken() const { return TokIdx; }
2882 void AdvanceToken() { ++TokIdx; }
2883 SourceLocation GetTokenLoc(unsigned tokI) {
2884 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2885 }
2886
Ted Kremenek6db61092010-05-05 00:55:15 +00002887public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002888 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002889 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2890 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002891 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002892 NumTokens(numTokens), TokIdx(0),
2893 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2894 Decl::MaxPCHLevel, RegionOfInterest),
2895 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002896
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002897 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002898 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002899 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002900};
2901}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002902
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002903void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2904 // Walk the AST within the region of interest, annotating tokens
2905 // along the way.
2906 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002907
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002908 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2909 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2910 if (Pos != Annotated.end())
2911 Cursors[I] = Pos->second;
2912 }
2913
2914 // Finish up annotating any tokens left.
2915 if (!MoreTokens())
2916 return;
2917
2918 const CXCursor &C = clang_getNullCursor();
2919 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2920 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2921 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002922 }
2923}
2924
Ted Kremenek6db61092010-05-05 00:55:15 +00002925enum CXChildVisitResult
2926AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002927 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2928 // We can always annotate a preprocessing directive/macro instantiation.
2929 if (clang_isPreprocessing(cursor.kind)) {
2930 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002931 return CXChildVisit_Recurse;
2932 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002933
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002934 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00002935
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002936 if (cursorRange.isInvalid())
2937 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002938
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002939 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2940
Ted Kremeneka333c662010-05-12 05:29:33 +00002941 // Adjust the annotated range based specific declarations.
2942 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2943 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002944 Decl *D = cxcursor::getCursorDecl(cursor);
2945 // Don't visit synthesized ObjC methods, since they have no syntatic
2946 // representation in the source.
2947 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2948 if (MD->isSynthesized())
2949 return CXChildVisit_Continue;
2950 }
2951 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002952 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2953 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002954 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002955 if (TLoc.isValid() &&
2956 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002957 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002958 }
2959 }
2960 }
2961
Ted Kremenek3f404602010-08-14 01:14:06 +00002962 // If the location of the cursor occurs within a macro instantiation, record
2963 // the spelling location of the cursor in our annotation map. We can then
2964 // paper over the token labelings during a post-processing step to try and
2965 // get cursor mappings for tokens that are the *arguments* of a macro
2966 // instantiation.
2967 if (L.isMacroID()) {
2968 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
2969 // Only invalidate the old annotation if it isn't part of a preprocessing
2970 // directive. Here we assume that the default construction of CXCursor
2971 // results in CXCursor.kind being an initialized value (i.e., 0). If
2972 // this isn't the case, we can fix by doing lookup + insertion.
2973
2974 CXCursor &oldC = Annotated[rawEncoding];
2975 if (!clang_isPreprocessing(oldC.kind))
2976 oldC = cursor;
2977 }
2978
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002979 const enum CXCursorKind K = clang_getCursorKind(parent);
2980 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00002981 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
2982 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002983
2984 while (MoreTokens()) {
2985 const unsigned I = NextToken();
2986 SourceLocation TokLoc = GetTokenLoc(I);
2987 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2988 case RangeBefore:
2989 Cursors[I] = updateC;
2990 AdvanceToken();
2991 continue;
2992 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002993 case RangeOverlap:
2994 break;
2995 }
2996 break;
2997 }
2998
2999 // Visit children to get their cursor information.
3000 const unsigned BeforeChildren = NextToken();
3001 VisitChildren(cursor);
3002 const unsigned AfterChildren = NextToken();
3003
3004 // Adjust 'Last' to the last token within the extent of the cursor.
3005 while (MoreTokens()) {
3006 const unsigned I = NextToken();
3007 SourceLocation TokLoc = GetTokenLoc(I);
3008 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3009 case RangeBefore:
3010 assert(0 && "Infeasible");
3011 case RangeAfter:
3012 break;
3013 case RangeOverlap:
3014 Cursors[I] = updateC;
3015 AdvanceToken();
3016 continue;
3017 }
3018 break;
3019 }
3020 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003021
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003022 // Scan the tokens that are at the beginning of the cursor, but are not
3023 // capture by the child cursors.
3024
3025 // For AST elements within macros, rely on a post-annotate pass to
3026 // to correctly annotate the tokens with cursors. Otherwise we can
3027 // get confusing results of having tokens that map to cursors that really
3028 // are expanded by an instantiation.
3029 if (L.isMacroID())
3030 cursor = clang_getNullCursor();
3031
3032 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3033 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3034 break;
3035 Cursors[I] = cursor;
3036 }
3037 // Scan the tokens that are at the end of the cursor, but are not captured
3038 // but the child cursors.
3039 for (unsigned I = AfterChildren; I != Last; ++I)
3040 Cursors[I] = cursor;
3041
3042 TokIdx = Last;
3043 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003044}
3045
Ted Kremenek6db61092010-05-05 00:55:15 +00003046static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3047 CXCursor parent,
3048 CXClientData client_data) {
3049 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3050}
3051
3052extern "C" {
3053
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003054void clang_annotateTokens(CXTranslationUnit TU,
3055 CXToken *Tokens, unsigned NumTokens,
3056 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003057
3058 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003059 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003060
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003061 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003062 if (!CXXUnit) {
3063 // Any token we don't specifically annotate will have a NULL cursor.
3064 const CXCursor &C = clang_getNullCursor();
3065 for (unsigned I = 0; I != NumTokens; ++I)
3066 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003067 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003068 }
3069
Douglas Gregorbdf60622010-03-05 21:16:25 +00003070 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003071
Douglas Gregor0396f462010-03-19 05:22:59 +00003072 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003073 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003074 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3075 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003076 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3077 clang_getTokenLocation(TU,
3078 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003079
Douglas Gregor0396f462010-03-19 05:22:59 +00003080 // A mapping from the source locations found when re-lexing or traversing the
3081 // region of interest to the corresponding cursors.
3082 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003083
3084 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003085 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003086 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3087 std::pair<FileID, unsigned> BeginLocInfo
3088 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3089 std::pair<FileID, unsigned> EndLocInfo
3090 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003091
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003092 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003093 bool Invalid = false;
3094 if (BeginLocInfo.first == EndLocInfo.first &&
3095 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3096 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003097 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3098 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003099 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003100 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003101 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003102
3103 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003104 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003105 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003106 Token Tok;
3107 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003108
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003109 reprocess:
3110 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3111 // We have found a preprocessing directive. Gobble it up so that we
3112 // don't see it while preprocessing these tokens later, but keep track of
3113 // all of the token locations inside this preprocessing directive so that
3114 // we can annotate them appropriately.
3115 //
3116 // FIXME: Some simple tests here could identify macro definitions and
3117 // #undefs, to provide specific cursor kinds for those.
3118 std::vector<SourceLocation> Locations;
3119 do {
3120 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003121 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003122 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003123
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003124 using namespace cxcursor;
3125 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003126 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3127 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003128 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003129 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3130 Annotated[Locations[I].getRawEncoding()] = Cursor;
3131 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003132
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003133 if (Tok.isAtStartOfLine())
3134 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003135
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003136 continue;
3137 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003138
Douglas Gregor48072312010-03-18 15:23:44 +00003139 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003140 break;
3141 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003142 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003143
Douglas Gregor0396f462010-03-19 05:22:59 +00003144 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003145 // a specific cursor.
3146 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3147 CXXUnit, RegionOfInterest);
3148 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003149}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003150} // end: extern "C"
3151
3152//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003153// Operations for querying linkage of a cursor.
3154//===----------------------------------------------------------------------===//
3155
3156extern "C" {
3157CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003158 if (!clang_isDeclaration(cursor.kind))
3159 return CXLinkage_Invalid;
3160
Ted Kremenek16b42592010-03-03 06:36:57 +00003161 Decl *D = cxcursor::getCursorDecl(cursor);
3162 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3163 switch (ND->getLinkage()) {
3164 case NoLinkage: return CXLinkage_NoLinkage;
3165 case InternalLinkage: return CXLinkage_Internal;
3166 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3167 case ExternalLinkage: return CXLinkage_External;
3168 };
3169
3170 return CXLinkage_Invalid;
3171}
3172} // end: extern "C"
3173
3174//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003175// Operations for querying language of a cursor.
3176//===----------------------------------------------------------------------===//
3177
3178static CXLanguageKind getDeclLanguage(const Decl *D) {
3179 switch (D->getKind()) {
3180 default:
3181 break;
3182 case Decl::ImplicitParam:
3183 case Decl::ObjCAtDefsField:
3184 case Decl::ObjCCategory:
3185 case Decl::ObjCCategoryImpl:
3186 case Decl::ObjCClass:
3187 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003188 case Decl::ObjCForwardProtocol:
3189 case Decl::ObjCImplementation:
3190 case Decl::ObjCInterface:
3191 case Decl::ObjCIvar:
3192 case Decl::ObjCMethod:
3193 case Decl::ObjCProperty:
3194 case Decl::ObjCPropertyImpl:
3195 case Decl::ObjCProtocol:
3196 return CXLanguage_ObjC;
3197 case Decl::CXXConstructor:
3198 case Decl::CXXConversion:
3199 case Decl::CXXDestructor:
3200 case Decl::CXXMethod:
3201 case Decl::CXXRecord:
3202 case Decl::ClassTemplate:
3203 case Decl::ClassTemplatePartialSpecialization:
3204 case Decl::ClassTemplateSpecialization:
3205 case Decl::Friend:
3206 case Decl::FriendTemplate:
3207 case Decl::FunctionTemplate:
3208 case Decl::LinkageSpec:
3209 case Decl::Namespace:
3210 case Decl::NamespaceAlias:
3211 case Decl::NonTypeTemplateParm:
3212 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003213 case Decl::TemplateTemplateParm:
3214 case Decl::TemplateTypeParm:
3215 case Decl::UnresolvedUsingTypename:
3216 case Decl::UnresolvedUsingValue:
3217 case Decl::Using:
3218 case Decl::UsingDirective:
3219 case Decl::UsingShadow:
3220 return CXLanguage_CPlusPlus;
3221 }
3222
3223 return CXLanguage_C;
3224}
3225
3226extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003227
3228enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3229 if (clang_isDeclaration(cursor.kind))
3230 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3231 if (D->hasAttr<UnavailableAttr>() ||
3232 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3233 return CXAvailability_Available;
3234
3235 if (D->hasAttr<DeprecatedAttr>())
3236 return CXAvailability_Deprecated;
3237 }
3238
3239 return CXAvailability_Available;
3240}
3241
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003242CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3243 if (clang_isDeclaration(cursor.kind))
3244 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3245
3246 return CXLanguage_Invalid;
3247}
3248} // end: extern "C"
3249
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003250
3251//===----------------------------------------------------------------------===//
3252// C++ AST instrospection.
3253//===----------------------------------------------------------------------===//
3254
3255extern "C" {
3256unsigned clang_CXXMethod_isStatic(CXCursor C) {
3257 if (!clang_isDeclaration(C.kind))
3258 return 0;
3259 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
3260 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003261}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003262
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003263} // end: extern "C"
3264
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003265//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003266// Attribute introspection.
3267//===----------------------------------------------------------------------===//
3268
3269extern "C" {
3270CXType clang_getIBOutletCollectionType(CXCursor C) {
3271 if (C.kind != CXCursor_IBOutletCollectionAttr)
3272 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3273
3274 IBOutletCollectionAttr *A =
3275 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3276
3277 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3278}
3279} // end: extern "C"
3280
3281//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003282// CXString Operations.
3283//===----------------------------------------------------------------------===//
3284
3285extern "C" {
3286const char *clang_getCString(CXString string) {
3287 return string.Spelling;
3288}
3289
3290void clang_disposeString(CXString string) {
3291 if (string.MustFreeString && string.Spelling)
3292 free((void*)string.Spelling);
3293}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003294
Ted Kremenekfb480492010-01-13 21:46:36 +00003295} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003296
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003297namespace clang { namespace cxstring {
3298CXString createCXString(const char *String, bool DupString){
3299 CXString Str;
3300 if (DupString) {
3301 Str.Spelling = strdup(String);
3302 Str.MustFreeString = 1;
3303 } else {
3304 Str.Spelling = String;
3305 Str.MustFreeString = 0;
3306 }
3307 return Str;
3308}
3309
3310CXString createCXString(llvm::StringRef String, bool DupString) {
3311 CXString Result;
3312 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3313 char *Spelling = (char *)malloc(String.size() + 1);
3314 memmove(Spelling, String.data(), String.size());
3315 Spelling[String.size()] = 0;
3316 Result.Spelling = Spelling;
3317 Result.MustFreeString = 1;
3318 } else {
3319 Result.Spelling = String.data();
3320 Result.MustFreeString = 0;
3321 }
3322 return Result;
3323}
3324}}
3325
Ted Kremenek04bb7162010-01-22 22:44:15 +00003326//===----------------------------------------------------------------------===//
3327// Misc. utility functions.
3328//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003329
Ted Kremenek04bb7162010-01-22 22:44:15 +00003330extern "C" {
3331
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003332CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003333 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003334}
3335
3336} // end: extern "C"