blob: ae53c16be0775f809123aec5942123068bfb933f [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 Gregor74dbe642010-08-31 19:31:58 +0000293 bool VisitClassTemplatePartialSpecializationDecl(
294 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000295 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000296 bool VisitEnumConstantDecl(EnumConstantDecl *D);
297 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
298 bool VisitFunctionDecl(FunctionDecl *ND);
299 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000300 bool VisitVarDecl(VarDecl *);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000301 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000302 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000303 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
304 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
305 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
306 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000307 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000308 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
309 bool VisitObjCImplDecl(ObjCImplDecl *D);
310 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
311 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
312 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
313 // etc.
314 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
315 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
316 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000317 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000318 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000319
Douglas Gregor01829d32010-08-31 14:41:23 +0000320 // Name visitor
321 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
322
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000323 // Template visitors
324 bool VisitTemplateParameters(const TemplateParameterList *Params);
325 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
326
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000327 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000328 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000329 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000330 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000331 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
332 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000333 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000334 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000335 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000336 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
337 bool VisitPointerTypeLoc(PointerTypeLoc TL);
338 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
339 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
340 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
341 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000342 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000343 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000344 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000345 // FIXME: Implement visitors here when the unimplemented TypeLocs get
346 // implemented
347 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
348 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000349
Douglas Gregora59e3902010-01-21 23:27:09 +0000350 // Statement visitors
351 bool VisitStmt(Stmt *S);
352 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000353 // FIXME: LabelStmt label?
354 bool VisitIfStmt(IfStmt *S);
355 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000356 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000357 bool VisitWhileStmt(WhileStmt *S);
358 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000359// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000360
Douglas Gregor336fd812010-01-23 00:40:08 +0000361 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000362 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
363 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000364 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000365 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000366 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000367 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000368 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000369 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000370 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000371 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000372 // FIXME: AddrLabelExpr (once we have cursors for labels)
373 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
374 bool VisitVAArgExpr(VAArgExpr *E);
375 // FIXME: InitListExpr (for the designators)
376 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000377};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000378
Ted Kremenekab188932010-01-05 19:32:54 +0000379} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000380
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000381static SourceRange getRawCursorExtent(CXCursor C);
382
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000383RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000384 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
385}
386
Douglas Gregorb1373d02010-01-20 20:59:29 +0000387/// \brief Visit the given cursor and, if requested by the visitor,
388/// its children.
389///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000390/// \param Cursor the cursor to visit.
391///
392/// \param CheckRegionOfInterest if true, then the caller already checked that
393/// this cursor is within the region of interest.
394///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395/// \returns true if the visitation should be aborted, false if it
396/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000397bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000398 if (clang_isInvalid(Cursor.kind))
399 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000400
Douglas Gregorb1373d02010-01-20 20:59:29 +0000401 if (clang_isDeclaration(Cursor.kind)) {
402 Decl *D = getCursorDecl(Cursor);
403 assert(D && "Invalid declaration cursor");
404 if (D->getPCHLevel() > MaxPCHLevel)
405 return false;
406
407 if (D->isImplicit())
408 return false;
409 }
410
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000411 // If we have a range of interest, and this cursor doesn't intersect with it,
412 // we're done.
413 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000414 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000415 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000416 return false;
417 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000418
Douglas Gregorb1373d02010-01-20 20:59:29 +0000419 switch (Visitor(Cursor, Parent, ClientData)) {
420 case CXChildVisit_Break:
421 return true;
422
423 case CXChildVisit_Continue:
424 return false;
425
426 case CXChildVisit_Recurse:
427 return VisitChildren(Cursor);
428 }
429
Douglas Gregorfd643772010-01-25 16:45:46 +0000430 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000431}
432
Douglas Gregor788f5a12010-03-20 00:41:21 +0000433std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
434CursorVisitor::getPreprocessedEntities() {
435 PreprocessingRecord &PPRec
436 = *TU->getPreprocessor().getPreprocessingRecord();
437
438 bool OnlyLocalDecls
439 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
440
441 // There is no region of interest; we have to walk everything.
442 if (RegionOfInterest.isInvalid())
443 return std::make_pair(PPRec.begin(OnlyLocalDecls),
444 PPRec.end(OnlyLocalDecls));
445
446 // Find the file in which the region of interest lands.
447 SourceManager &SM = TU->getSourceManager();
448 std::pair<FileID, unsigned> Begin
449 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
450 std::pair<FileID, unsigned> End
451 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
452
453 // The region of interest spans files; we have to walk everything.
454 if (Begin.first != End.first)
455 return std::make_pair(PPRec.begin(OnlyLocalDecls),
456 PPRec.end(OnlyLocalDecls));
457
458 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
459 = TU->getPreprocessedEntitiesByFile();
460 if (ByFileMap.empty()) {
461 // Build the mapping from files to sets of preprocessed entities.
462 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
463 EEnd = PPRec.end(OnlyLocalDecls);
464 E != EEnd; ++E) {
465 std::pair<FileID, unsigned> P
466 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
467 ByFileMap[P.first].push_back(*E);
468 }
469 }
470
471 return std::make_pair(ByFileMap[Begin.first].begin(),
472 ByFileMap[Begin.first].end());
473}
474
Douglas Gregorb1373d02010-01-20 20:59:29 +0000475/// \brief Visit the children of the given cursor.
476///
477/// \returns true if the visitation should be aborted, false if it
478/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000479bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000480 if (clang_isReference(Cursor.kind)) {
481 // By definition, references have no children.
482 return false;
483 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000484
485 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000486 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000487 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000488
Douglas Gregorb1373d02010-01-20 20:59:29 +0000489 if (clang_isDeclaration(Cursor.kind)) {
490 Decl *D = getCursorDecl(Cursor);
491 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000492 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000493 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000494
Douglas Gregora59e3902010-01-21 23:27:09 +0000495 if (clang_isStatement(Cursor.kind))
496 return Visit(getCursorStmt(Cursor));
497 if (clang_isExpression(Cursor.kind))
498 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000499
Douglas Gregorb1373d02010-01-20 20:59:29 +0000500 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000501 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000502 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
503 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000504 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
505 TLEnd = CXXUnit->top_level_end();
506 TL != TLEnd; ++TL) {
507 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000508 return true;
509 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000510 } else if (VisitDeclContext(
511 CXXUnit->getASTContext().getTranslationUnitDecl()))
512 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000513
Douglas Gregor0396f462010-03-19 05:22:59 +0000514 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000515 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000516 // FIXME: Once we have the ability to deserialize a preprocessing record,
517 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000518 PreprocessingRecord::iterator E, EEnd;
519 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000520 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
521 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
522 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000523
Douglas Gregor0396f462010-03-19 05:22:59 +0000524 continue;
525 }
526
527 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
528 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
529 return true;
530
531 continue;
532 }
533 }
534 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000535 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000536 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000537
Douglas Gregorb1373d02010-01-20 20:59:29 +0000538 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000539 return false;
540}
541
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000542bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000543 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
544 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000545
Ted Kremenek664cffd2010-07-22 11:30:19 +0000546 if (Stmt *Body = B->getBody())
547 return Visit(MakeCXCursor(Body, StmtParent, TU));
548
549 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000550}
551
Douglas Gregorb1373d02010-01-20 20:59:29 +0000552bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000553 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000554 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000555
Ted Kremenek23173d72010-05-18 21:09:07 +0000556 Decl *D = *I;
557 if (D->getLexicalDeclContext() != DC)
558 continue;
559
560 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000561
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000562 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000563 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000564 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000565 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000566
567 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000568 case RangeBefore:
569 // This declaration comes before the region of interest; skip it.
570 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000571
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000572 case RangeAfter:
573 // This declaration comes after the region of interest; we're done.
574 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000575
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000576 case RangeOverlap:
577 // This declaration overlaps the region of interest; visit it.
578 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000579 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000580 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000581
Daniel Dunbard52864b2010-02-14 10:02:57 +0000582 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000583 return true;
584 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000585
Douglas Gregorb1373d02010-01-20 20:59:29 +0000586 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000587}
588
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000589bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
590 llvm_unreachable("Translation units are visited directly by Visit()");
591 return false;
592}
593
594bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
595 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
596 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598 return false;
599}
600
601bool CursorVisitor::VisitTagDecl(TagDecl *D) {
602 return VisitDeclContext(D);
603}
604
Douglas Gregor74dbe642010-08-31 19:31:58 +0000605bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
606 ClassTemplatePartialSpecializationDecl *D) {
607 // FIXME: Visit the "outer" template parameter lists on the TagDecl
608 // before visiting these template parameters.
609 if (VisitTemplateParameters(D->getTemplateParameters()))
610 return true;
611
612 // Visit the partial specialization arguments.
613 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
614 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
615 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
616 return true;
617
618 return VisitCXXRecordDecl(D);
619}
620
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000621bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
622 // FIXME: Visit default argument
623 return false;
624}
625
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000626bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
627 if (Expr *Init = D->getInitExpr())
628 return Visit(MakeCXCursor(Init, StmtParent, TU));
629 return false;
630}
631
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000632bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
633 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
634 if (Visit(TSInfo->getTypeLoc()))
635 return true;
636
637 return false;
638}
639
Douglas Gregorb1373d02010-01-20 20:59:29 +0000640bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000641 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
642 // Visit the function declaration's syntactic components in the order
643 // written. This requires a bit of work.
644 TypeLoc TL = TSInfo->getTypeLoc();
645 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
646
647 // If we have a function declared directly (without the use of a typedef),
648 // visit just the return type. Otherwise, just visit the function's type
649 // now.
650 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
651 (!FTL && Visit(TL)))
652 return true;
653
654 // FIXME: Visit the nested-name-specifier, if present.
655
656 // Visit the declaration name.
657 if (VisitDeclarationNameInfo(ND->getNameInfo()))
658 return true;
659
660 // FIXME: Visit explicitly-specified template arguments!
661
662 // Visit the function parameters, if we have a function type.
663 if (FTL && VisitFunctionTypeLoc(*FTL, true))
664 return true;
665
666 // FIXME: Attributes?
667 }
668
Douglas Gregora59e3902010-01-21 23:27:09 +0000669 if (ND->isThisDeclarationADefinition() &&
670 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
671 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000672
Douglas Gregorb1373d02010-01-20 20:59:29 +0000673 return false;
674}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000675
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000676bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
677 if (VisitDeclaratorDecl(D))
678 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000679
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000680 if (Expr *BitWidth = D->getBitWidth())
681 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000682
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000683 return false;
684}
685
686bool CursorVisitor::VisitVarDecl(VarDecl *D) {
687 if (VisitDeclaratorDecl(D))
688 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000689
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000690 if (Expr *Init = D->getInit())
691 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000692
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000693 return false;
694}
695
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000696bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
697 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
698 // before visiting these template parameters.
699 if (VisitTemplateParameters(D->getTemplateParameters()))
700 return true;
701
702 return VisitFunctionDecl(D->getTemplatedDecl());
703}
704
Douglas Gregor39d6f072010-08-31 19:02:00 +0000705bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
706 // FIXME: Visit the "outer" template parameter lists on the TagDecl
707 // before visiting these template parameters.
708 if (VisitTemplateParameters(D->getTemplateParameters()))
709 return true;
710
711 return VisitCXXRecordDecl(D->getTemplatedDecl());
712}
713
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000714bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000715 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
716 if (Visit(TSInfo->getTypeLoc()))
717 return true;
718
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000719 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000720 PEnd = ND->param_end();
721 P != PEnd; ++P) {
722 if (Visit(MakeCXCursor(*P, TU)))
723 return true;
724 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000725
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000726 if (ND->isThisDeclarationADefinition() &&
727 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
728 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000729
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000730 return false;
731}
732
Douglas Gregora59e3902010-01-21 23:27:09 +0000733bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
734 return VisitDeclContext(D);
735}
736
Douglas Gregorb1373d02010-01-20 20:59:29 +0000737bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000738 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
739 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000740 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000741
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000742 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
743 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
744 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000745 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000746 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000747
Douglas Gregora59e3902010-01-21 23:27:09 +0000748 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000749}
750
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000751bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
752 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
753 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
754 E = PID->protocol_end(); I != E; ++I, ++PL)
755 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
756 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000757
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000758 return VisitObjCContainerDecl(PID);
759}
760
Ted Kremenek23173d72010-05-18 21:09:07 +0000761bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000762 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
763 return true;
764
Ted Kremenek23173d72010-05-18 21:09:07 +0000765 // FIXME: This implements a workaround with @property declarations also being
766 // installed in the DeclContext for the @interface. Eventually this code
767 // should be removed.
768 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
769 if (!CDecl || !CDecl->IsClassExtension())
770 return false;
771
772 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
773 if (!ID)
774 return false;
775
776 IdentifierInfo *PropertyId = PD->getIdentifier();
777 ObjCPropertyDecl *prevDecl =
778 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
779
780 if (!prevDecl)
781 return false;
782
783 // Visit synthesized methods since they will be skipped when visiting
784 // the @interface.
785 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
786 if (MD->isSynthesized())
787 if (Visit(MakeCXCursor(MD, TU)))
788 return true;
789
790 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
791 if (MD->isSynthesized())
792 if (Visit(MakeCXCursor(MD, TU)))
793 return true;
794
795 return false;
796}
797
Douglas Gregorb1373d02010-01-20 20:59:29 +0000798bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000799 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000800 if (D->getSuperClass() &&
801 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000802 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000803 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000804 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000805
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000806 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
807 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
808 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000809 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000810 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000811
Douglas Gregora59e3902010-01-21 23:27:09 +0000812 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000813}
814
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000815bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
816 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000817}
818
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000819bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000820 // 'ID' could be null when dealing with invalid code.
821 if (ObjCInterfaceDecl *ID = D->getClassInterface())
822 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
823 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000824
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000825 return VisitObjCImplDecl(D);
826}
827
828bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
829#if 0
830 // Issue callbacks for super class.
831 // FIXME: No source location information!
832 if (D->getSuperClass() &&
833 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000834 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000835 TU)))
836 return true;
837#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000838
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000839 return VisitObjCImplDecl(D);
840}
841
842bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
843 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
844 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
845 E = D->protocol_end();
846 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000847 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000848 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000849
850 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000851}
852
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000853bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
854 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
855 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
856 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000857
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000858 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000859}
860
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000861bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
862 return VisitDeclContext(D);
863}
864
Douglas Gregor01829d32010-08-31 14:41:23 +0000865bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
866 switch (Name.getName().getNameKind()) {
867 case clang::DeclarationName::Identifier:
868 case clang::DeclarationName::CXXLiteralOperatorName:
869 case clang::DeclarationName::CXXOperatorName:
870 case clang::DeclarationName::CXXUsingDirective:
871 return false;
872
873 case clang::DeclarationName::CXXConstructorName:
874 case clang::DeclarationName::CXXDestructorName:
875 case clang::DeclarationName::CXXConversionFunctionName:
876 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
877 return Visit(TSInfo->getTypeLoc());
878 return false;
879
880 case clang::DeclarationName::ObjCZeroArgSelector:
881 case clang::DeclarationName::ObjCOneArgSelector:
882 case clang::DeclarationName::ObjCMultiArgSelector:
883 // FIXME: Per-identifier location info?
884 return false;
885 }
886
887 return false;
888}
889
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000890bool CursorVisitor::VisitTemplateParameters(
891 const TemplateParameterList *Params) {
892 if (!Params)
893 return false;
894
895 for (TemplateParameterList::const_iterator P = Params->begin(),
896 PEnd = Params->end();
897 P != PEnd; ++P) {
898 if (Visit(MakeCXCursor(*P, TU)))
899 return true;
900 }
901
902 return false;
903}
904
905bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
906 switch (TAL.getArgument().getKind()) {
907 case TemplateArgument::Null:
908 case TemplateArgument::Integral:
909 return false;
910
911 case TemplateArgument::Pack:
912 // FIXME: Implement when variadic templates come along.
913 return false;
914
915 case TemplateArgument::Type:
916 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
917 return Visit(TSInfo->getTypeLoc());
918 return false;
919
920 case TemplateArgument::Declaration:
921 if (Expr *E = TAL.getSourceDeclExpression())
922 return Visit(MakeCXCursor(E, StmtParent, TU));
923 return false;
924
925 case TemplateArgument::Expression:
926 if (Expr *E = TAL.getSourceExpression())
927 return Visit(MakeCXCursor(E, StmtParent, TU));
928 return false;
929
930 case TemplateArgument::Template:
931 // FIXME: Visit template name.
932 return false;
933 }
934
935 return false;
936}
937
Ted Kremeneka0536d82010-05-07 01:04:29 +0000938bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
939 return VisitDeclContext(D);
940}
941
Douglas Gregor01829d32010-08-31 14:41:23 +0000942bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
943 return Visit(TL.getUnqualifiedLoc());
944}
945
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000946bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
947 ASTContext &Context = TU->getASTContext();
948
949 // Some builtin types (such as Objective-C's "id", "sel", and
950 // "Class") have associated declarations. Create cursors for those.
951 QualType VisitType;
952 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000953 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000954 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000955 case BuiltinType::Char_U:
956 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000957 case BuiltinType::Char16:
958 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000959 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000960 case BuiltinType::UInt:
961 case BuiltinType::ULong:
962 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000963 case BuiltinType::UInt128:
964 case BuiltinType::Char_S:
965 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000966 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000967 case BuiltinType::Short:
968 case BuiltinType::Int:
969 case BuiltinType::Long:
970 case BuiltinType::LongLong:
971 case BuiltinType::Int128:
972 case BuiltinType::Float:
973 case BuiltinType::Double:
974 case BuiltinType::LongDouble:
975 case BuiltinType::NullPtr:
976 case BuiltinType::Overload:
977 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000978 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000979
980 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000981 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000982
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000983 case BuiltinType::ObjCId:
984 VisitType = Context.getObjCIdType();
985 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000986
987 case BuiltinType::ObjCClass:
988 VisitType = Context.getObjCClassType();
989 break;
990
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000991 case BuiltinType::ObjCSel:
992 VisitType = Context.getObjCSelType();
993 break;
994 }
995
996 if (!VisitType.isNull()) {
997 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000998 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000999 TU));
1000 }
1001
1002 return false;
1003}
1004
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001005bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1006 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1007}
1008
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001009bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1010 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1011}
1012
1013bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1014 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1015}
1016
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001017bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1018 // FIXME: We can't visit the template template parameter, but there's
1019 // no context information with which we can match up the depth/index in the
1020 // type to the appropriate
1021 return false;
1022}
1023
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001024bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1025 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1026 return true;
1027
John McCallc12c5bb2010-05-15 11:32:37 +00001028 return false;
1029}
1030
1031bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1032 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1033 return true;
1034
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001035 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1036 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1037 TU)))
1038 return true;
1039 }
1040
1041 return false;
1042}
1043
1044bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001045 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001046}
1047
1048bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1049 return Visit(TL.getPointeeLoc());
1050}
1051
1052bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1053 return Visit(TL.getPointeeLoc());
1054}
1055
1056bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1057 return Visit(TL.getPointeeLoc());
1058}
1059
1060bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001061 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001062}
1063
1064bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001065 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001066}
1067
Douglas Gregor01829d32010-08-31 14:41:23 +00001068bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1069 bool SkipResultType) {
1070 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001071 return true;
1072
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001073 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001074 if (Decl *D = TL.getArg(I))
1075 if (Visit(MakeCXCursor(D, TU)))
1076 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001077
1078 return false;
1079}
1080
1081bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1082 if (Visit(TL.getElementLoc()))
1083 return true;
1084
1085 if (Expr *Size = TL.getSizeExpr())
1086 return Visit(MakeCXCursor(Size, StmtParent, TU));
1087
1088 return false;
1089}
1090
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001091bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1092 TemplateSpecializationTypeLoc TL) {
1093 // FIXME: Visit the template name.
1094
1095 // Visit the template arguments.
1096 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1097 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1098 return true;
1099
1100 return false;
1101}
1102
Douglas Gregor2332c112010-01-21 20:48:56 +00001103bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1104 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1105}
1106
1107bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1108 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1109 return Visit(TSInfo->getTypeLoc());
1110
1111 return false;
1112}
1113
Douglas Gregora59e3902010-01-21 23:27:09 +00001114bool CursorVisitor::VisitStmt(Stmt *S) {
1115 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1116 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001117 if (Stmt *C = *Child)
1118 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1119 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001120 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001121
Douglas Gregora59e3902010-01-21 23:27:09 +00001122 return false;
1123}
1124
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001125bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1126 // Specially handle CaseStmts because they can be nested, e.g.:
1127 //
1128 // case 1:
1129 // case 2:
1130 //
1131 // In this case the second CaseStmt is the child of the first. Walking
1132 // these recursively can blow out the stack.
1133 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1134 while (true) {
1135 // Set the Parent field to Cursor, then back to its old value once we're
1136 // done.
1137 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1138
1139 if (Stmt *LHS = S->getLHS())
1140 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1141 return true;
1142 if (Stmt *RHS = S->getRHS())
1143 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1144 return true;
1145 if (Stmt *SubStmt = S->getSubStmt()) {
1146 if (!isa<CaseStmt>(SubStmt))
1147 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1148
1149 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1150 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1151 Cursor = MakeCXCursor(CS, StmtParent, TU);
1152 if (RegionOfInterest.isValid()) {
1153 SourceRange Range = CS->getSourceRange();
1154 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1155 return false;
1156 }
1157
1158 switch (Visitor(Cursor, Parent, ClientData)) {
1159 case CXChildVisit_Break: return true;
1160 case CXChildVisit_Continue: return false;
1161 case CXChildVisit_Recurse:
1162 // Perform tail-recursion manually.
1163 S = CS;
1164 continue;
1165 }
1166 }
1167 return false;
1168 }
1169}
1170
Douglas Gregora59e3902010-01-21 23:27:09 +00001171bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1172 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1173 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001174 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001175 return true;
1176 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001177
Douglas Gregora59e3902010-01-21 23:27:09 +00001178 return false;
1179}
1180
Douglas Gregorf5bab412010-01-22 01:00:11 +00001181bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1182 if (VarDecl *Var = S->getConditionVariable()) {
1183 if (Visit(MakeCXCursor(Var, TU)))
1184 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001185 }
1186
Douglas Gregor263b47b2010-01-25 16:12:32 +00001187 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1188 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001189 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1190 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001191 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1192 return true;
1193
1194 return false;
1195}
1196
1197bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1198 if (VarDecl *Var = S->getConditionVariable()) {
1199 if (Visit(MakeCXCursor(Var, TU)))
1200 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001201 }
1202
Douglas Gregor263b47b2010-01-25 16:12:32 +00001203 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1204 return true;
1205 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1206 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001207
Douglas Gregor263b47b2010-01-25 16:12:32 +00001208 return false;
1209}
1210
1211bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1212 if (VarDecl *Var = S->getConditionVariable()) {
1213 if (Visit(MakeCXCursor(Var, TU)))
1214 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001215 }
1216
Douglas Gregor263b47b2010-01-25 16:12:32 +00001217 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1218 return true;
1219 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001220 return true;
1221
Douglas Gregor263b47b2010-01-25 16:12:32 +00001222 return false;
1223}
1224
1225bool CursorVisitor::VisitForStmt(ForStmt *S) {
1226 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1227 return true;
1228 if (VarDecl *Var = S->getConditionVariable()) {
1229 if (Visit(MakeCXCursor(Var, TU)))
1230 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001231 }
1232
Douglas Gregor263b47b2010-01-25 16:12:32 +00001233 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1234 return true;
1235 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1236 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001237 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1238 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001239
Douglas Gregorf5bab412010-01-22 01:00:11 +00001240 return false;
1241}
1242
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001243bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1244 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1245 return true;
1246
1247 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1248 return true;
1249
1250 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1251 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1252 return true;
1253
1254 return false;
1255}
1256
Ted Kremenek3064ef92010-08-27 21:34:58 +00001257bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1258 if (D->isDefinition()) {
1259 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1260 E = D->bases_end(); I != E; ++I) {
1261 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1262 return true;
1263 }
1264 }
1265
1266 return VisitTagDecl(D);
1267}
1268
1269
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001270bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1271 return Visit(B->getBlockDecl());
1272}
1273
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001274bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1275 // FIXME: Visit fields as well?
1276 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1277 return true;
1278
1279 return VisitExpr(E);
1280}
1281
Douglas Gregor336fd812010-01-23 00:40:08 +00001282bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1283 if (E->isArgumentType()) {
1284 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1285 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001286
Douglas Gregor336fd812010-01-23 00:40:08 +00001287 return false;
1288 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001289
Douglas Gregor336fd812010-01-23 00:40:08 +00001290 return VisitExpr(E);
1291}
1292
1293bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1294 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1295 if (Visit(TSInfo->getTypeLoc()))
1296 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001297
Douglas Gregor336fd812010-01-23 00:40:08 +00001298 return VisitCastExpr(E);
1299}
1300
1301bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1302 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1303 if (Visit(TSInfo->getTypeLoc()))
1304 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001305
Douglas Gregor336fd812010-01-23 00:40:08 +00001306 return VisitExpr(E);
1307}
1308
Douglas Gregor648220e2010-08-10 15:02:34 +00001309bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1310 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1311 Visit(E->getArgTInfo2()->getTypeLoc());
1312}
1313
1314bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1315 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1316 return true;
1317
1318 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1319}
1320
Douglas Gregorc2350e52010-03-08 16:40:19 +00001321bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001322 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1323 if (Visit(TSInfo->getTypeLoc()))
1324 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001325
1326 return VisitExpr(E);
1327}
1328
Douglas Gregor81d34662010-04-20 15:39:42 +00001329bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1330 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1331}
1332
1333
Ted Kremenek09dfa372010-02-18 05:46:33 +00001334bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001335 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1336 i != e; ++i)
1337 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001338 return true;
1339
1340 return false;
1341}
1342
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001343extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001344CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1345 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001346 // We use crash recovery to make some of our APIs more reliable, implicitly
1347 // enable it.
1348 llvm::CrashRecoveryContext::Enable();
1349
Douglas Gregora030b7c2010-01-22 20:35:53 +00001350 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001351 if (excludeDeclarationsFromPCH)
1352 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001353 if (displayDiagnostics)
1354 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001355 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001356}
1357
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001358void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001359 if (CIdx)
1360 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001361 if (getenv("LIBCLANG_TIMING"))
1362 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001363}
1364
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001365void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001366 if (CIdx) {
1367 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1368 CXXIdx->setUseExternalASTGeneration(value);
1369 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001370}
1371
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001372CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001373 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001374 if (!CIdx)
1375 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001376
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001377 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001378
Douglas Gregor28019772010-04-05 23:52:57 +00001379 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001380 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001381 CXXIdx->getOnlyLocalDecls(),
1382 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001383}
1384
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001385unsigned clang_defaultEditingTranslationUnitOptions() {
1386 return CXTranslationUnit_PrecompiledPreamble;
1387}
1388
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001389CXTranslationUnit
1390clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1391 const char *source_filename,
1392 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001393 const char **command_line_args,
1394 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001395 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001396 return clang_parseTranslationUnit(CIdx, source_filename,
1397 command_line_args, num_command_line_args,
1398 unsaved_files, num_unsaved_files,
1399 CXTranslationUnit_DetailedPreprocessingRecord);
1400}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001401
1402struct ParseTranslationUnitInfo {
1403 CXIndex CIdx;
1404 const char *source_filename;
1405 const char **command_line_args;
1406 int num_command_line_args;
1407 struct CXUnsavedFile *unsaved_files;
1408 unsigned num_unsaved_files;
1409 unsigned options;
1410 CXTranslationUnit result;
1411};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001412static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001413 ParseTranslationUnitInfo *PTUI =
1414 static_cast<ParseTranslationUnitInfo*>(UserData);
1415 CXIndex CIdx = PTUI->CIdx;
1416 const char *source_filename = PTUI->source_filename;
1417 const char **command_line_args = PTUI->command_line_args;
1418 int num_command_line_args = PTUI->num_command_line_args;
1419 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1420 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1421 unsigned options = PTUI->options;
1422 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001423
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001424 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001425 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001426
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001427 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1428
Douglas Gregor44c181a2010-07-23 00:33:23 +00001429 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001430 bool CompleteTranslationUnit
1431 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001432 bool CacheCodeCompetionResults
1433 = options & CXTranslationUnit_CacheCompletionResults;
1434
Douglas Gregor5352ac02010-01-28 00:27:43 +00001435 // Configure the diagnostics.
1436 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001437 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1438 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001439
Douglas Gregor4db64a42010-01-23 00:14:00 +00001440 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1441 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001442 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001443 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001444 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001445 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1446 Buffer));
1447 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001448
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001449 if (!CXXIdx->getUseExternalASTGeneration()) {
1450 llvm::SmallVector<const char *, 16> Args;
1451
1452 // The 'source_filename' argument is optional. If the caller does not
1453 // specify it then it is assumed that the source file is specified
1454 // in the actual argument list.
1455 if (source_filename)
1456 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001457
1458 // Since the Clang C library is primarily used by batch tools dealing with
1459 // (often very broken) source code, where spell-checking can have a
1460 // significant negative impact on performance (particularly when
1461 // precompiled headers are involved), we disable it by default.
1462 // Note that we place this argument early in the list, so that it can be
1463 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001464 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001465
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001466 Args.insert(Args.end(), command_line_args,
1467 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001468
Douglas Gregor44c181a2010-07-23 00:33:23 +00001469 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001470 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1471 Args.push_back("-Xclang");
1472 Args.push_back("-detailed-preprocessing-record");
1473 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001474
Douglas Gregor5352ac02010-01-28 00:27:43 +00001475 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001476
Ted Kremenek29b72842010-01-07 22:49:05 +00001477#ifdef USE_CRASHTRACER
1478 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001479#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001480
Daniel Dunbar94220972009-12-05 02:17:18 +00001481 llvm::OwningPtr<ASTUnit> Unit(
1482 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001483 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001484 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001485 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001486 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001487 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001488 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001489 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001490 CompleteTranslationUnit,
1491 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001492
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001493 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001494 // Make sure to check that 'Unit' is non-NULL.
1495 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001496 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1497 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001498 D != DEnd; ++D) {
1499 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001500 CXString Msg = clang_formatDiagnostic(&Diag,
1501 clang_defaultDiagnosticDisplayOptions());
1502 fprintf(stderr, "%s\n", clang_getCString(Msg));
1503 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001504 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001505#ifdef LLVM_ON_WIN32
1506 // On Windows, force a flush, since there may be multiple copies of
1507 // stderr and stdout in the file system, all with different buffers
1508 // but writing to the same device.
1509 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001510#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001511 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001512 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001513
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001514 PTUI->result = Unit.take();
1515 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001516 }
1517
Ted Kremenek139ba862009-10-22 00:03:57 +00001518 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001519 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001520
Ted Kremenek139ba862009-10-22 00:03:57 +00001521 // First add the complete path to the 'clang' executable.
1522 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001523 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001524
Ted Kremenek139ba862009-10-22 00:03:57 +00001525 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001526 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001527
Ted Kremenek139ba862009-10-22 00:03:57 +00001528 // The 'source_filename' argument is optional. If the caller does not
1529 // specify it then it is assumed that the source file is specified
1530 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001531 if (source_filename)
1532 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001533
Steve Naroff37b5ac22009-10-15 20:50:09 +00001534 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001535 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001536 char astTmpFile[L_tmpnam];
1537 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001538
1539 // Since the Clang C library is primarily used by batch tools dealing with
1540 // (often very broken) source code, where spell-checking can have a
1541 // significant negative impact on performance (particularly when
1542 // precompiled headers are involved), we disable it by default.
1543 // Note that we place this argument early in the list, so that it can be
1544 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001545 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001546
Douglas Gregor4db64a42010-01-23 00:14:00 +00001547 // Remap any unsaved files to temporary files.
1548 std::vector<llvm::sys::Path> TemporaryFiles;
1549 std::vector<std::string> RemapArgs;
1550 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001551 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001552
Douglas Gregor4db64a42010-01-23 00:14:00 +00001553 // The pointers into the elements of RemapArgs are stable because we
1554 // won't be adding anything to RemapArgs after this point.
1555 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1556 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001557
Ted Kremenek139ba862009-10-22 00:03:57 +00001558 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1559 for (int i = 0; i < num_command_line_args; ++i)
1560 if (const char *arg = command_line_args[i]) {
1561 if (strcmp(arg, "-o") == 0) {
1562 ++i; // Also skip the matching argument.
1563 continue;
1564 }
1565 if (strcmp(arg, "-emit-ast") == 0 ||
1566 strcmp(arg, "-c") == 0 ||
1567 strcmp(arg, "-fsyntax-only") == 0) {
1568 continue;
1569 }
1570
1571 // Keep the argument.
1572 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001573 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001574
Douglas Gregord93256e2010-01-28 06:00:51 +00001575 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001576 char tmpFileResults[L_tmpnam];
1577 char *tmpResultsFileName = tmpnam(tmpFileResults);
1578 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001579 TemporaryFiles.push_back(DiagnosticsFile);
1580 argv.push_back("-fdiagnostics-binary");
1581
Douglas Gregor44c181a2010-07-23 00:33:23 +00001582 // Do we need the detailed preprocessing record?
1583 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1584 argv.push_back("-Xclang");
1585 argv.push_back("-detailed-preprocessing-record");
1586 }
1587
Ted Kremenek139ba862009-10-22 00:03:57 +00001588 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001589 argv.push_back(NULL);
1590
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001591 // Invoke 'clang'.
1592 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1593 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001594 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001595 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1596 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001597 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001598 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001599 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001600
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001601 if (!ErrMsg.empty()) {
1602 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001603 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001604 I != E; ++I) {
1605 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001606 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001607 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001608 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001609
Daniel Dunbar32141c82010-02-23 20:23:45 +00001610 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001611 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001612
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001613 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001614 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001615 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001616 RemappedFiles.size(),
1617 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001618 if (ATU) {
1619 LoadSerializedDiagnostics(DiagnosticsFile,
1620 num_unsaved_files, unsaved_files,
1621 ATU->getFileManager(),
1622 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001623 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001624 } else if (CXXIdx->getDisplayDiagnostics()) {
1625 // We failed to load the ASTUnit, but we can still deserialize the
1626 // diagnostics and emit them.
1627 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001628 Diagnostic Diag;
1629 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001630 // FIXME: Faked LangOpts!
1631 LangOptions LangOpts;
1632 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1633 LoadSerializedDiagnostics(DiagnosticsFile,
1634 num_unsaved_files, unsaved_files,
1635 FileMgr, SourceMgr, Diags);
1636 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1637 DEnd = Diags.end();
1638 D != DEnd; ++D) {
1639 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001640 CXString Msg = clang_formatDiagnostic(&Diag,
1641 clang_defaultDiagnosticDisplayOptions());
1642 fprintf(stderr, "%s\n", clang_getCString(Msg));
1643 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001644 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001645
1646#ifdef LLVM_ON_WIN32
1647 // On Windows, force a flush, since there may be multiple copies of
1648 // stderr and stdout in the file system, all with different buffers
1649 // but writing to the same device.
1650 fflush(stderr);
1651#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001652 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001653
Douglas Gregor313e26c2010-02-18 23:35:40 +00001654 if (ATU) {
1655 // Make the translation unit responsible for destroying all temporary files.
1656 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1657 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001658 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001659 } else {
1660 // Destroy all of the temporary files now; they can't be referenced any
1661 // longer.
1662 llvm::sys::Path(astTmpFile).eraseFromDisk();
1663 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1664 TemporaryFiles[i].eraseFromDisk();
1665 }
1666
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001667 PTUI->result = ATU;
1668}
1669CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1670 const char *source_filename,
1671 const char **command_line_args,
1672 int num_command_line_args,
1673 struct CXUnsavedFile *unsaved_files,
1674 unsigned num_unsaved_files,
1675 unsigned options) {
1676 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1677 num_command_line_args, unsaved_files, num_unsaved_files,
1678 options, 0 };
1679 llvm::CrashRecoveryContext CRC;
1680
1681 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001682 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1683 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1684 fprintf(stderr, " 'command_line_args' : [");
1685 for (int i = 0; i != num_command_line_args; ++i) {
1686 if (i)
1687 fprintf(stderr, ", ");
1688 fprintf(stderr, "'%s'", command_line_args[i]);
1689 }
1690 fprintf(stderr, "],\n");
1691 fprintf(stderr, " 'unsaved_files' : [");
1692 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1693 if (i)
1694 fprintf(stderr, ", ");
1695 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1696 unsaved_files[i].Length);
1697 }
1698 fprintf(stderr, "],\n");
1699 fprintf(stderr, " 'options' : %d,\n", options);
1700 fprintf(stderr, "}\n");
1701
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001702 return 0;
1703 }
1704
1705 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001706}
1707
Douglas Gregor19998442010-08-13 15:35:05 +00001708unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1709 return CXSaveTranslationUnit_None;
1710}
1711
1712int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1713 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001714 if (!TU)
1715 return 1;
1716
1717 return static_cast<ASTUnit *>(TU)->Save(FileName);
1718}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001719
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001720void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001721 if (CTUnit) {
1722 // If the translation unit has been marked as unsafe to free, just discard
1723 // it.
1724 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1725 return;
1726
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001727 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001728 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001729}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001730
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001731unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1732 return CXReparse_None;
1733}
1734
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001735struct ReparseTranslationUnitInfo {
1736 CXTranslationUnit TU;
1737 unsigned num_unsaved_files;
1738 struct CXUnsavedFile *unsaved_files;
1739 unsigned options;
1740 int result;
1741};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001742static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001743 ReparseTranslationUnitInfo *RTUI =
1744 static_cast<ReparseTranslationUnitInfo*>(UserData);
1745 CXTranslationUnit TU = RTUI->TU;
1746 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1747 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1748 unsigned options = RTUI->options;
1749 (void) options;
1750 RTUI->result = 1;
1751
Douglas Gregorabc563f2010-07-19 21:46:24 +00001752 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001753 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001754
1755 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1756 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1757 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1758 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001759 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001760 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1761 Buffer));
1762 }
1763
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001764 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1765 RemappedFiles.size()))
1766 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001767}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001768int clang_reparseTranslationUnit(CXTranslationUnit TU,
1769 unsigned num_unsaved_files,
1770 struct CXUnsavedFile *unsaved_files,
1771 unsigned options) {
1772 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1773 options, 0 };
1774 llvm::CrashRecoveryContext CRC;
1775
1776 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001777 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001778 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1779 return 1;
1780 }
1781
1782 return RTUI.result;
1783}
1784
Douglas Gregordf95a132010-08-09 20:45:32 +00001785
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001786CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001787 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001788 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001789
Steve Naroff77accc12009-09-03 18:19:54 +00001790 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001791 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001792}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001793
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001794CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001795 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001796 return Result;
1797}
1798
Ted Kremenekfb480492010-01-13 21:46:36 +00001799} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001800
Ted Kremenekfb480492010-01-13 21:46:36 +00001801//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001802// CXSourceLocation and CXSourceRange Operations.
1803//===----------------------------------------------------------------------===//
1804
Douglas Gregorb9790342010-01-22 21:44:22 +00001805extern "C" {
1806CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001807 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001808 return Result;
1809}
1810
1811unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001812 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1813 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1814 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001815}
1816
1817CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1818 CXFile file,
1819 unsigned line,
1820 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001821 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001822 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001823
Douglas Gregorb9790342010-01-22 21:44:22 +00001824 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1825 SourceLocation SLoc
1826 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001827 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001828 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001829
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001830 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001831}
1832
Douglas Gregor5352ac02010-01-28 00:27:43 +00001833CXSourceRange clang_getNullRange() {
1834 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1835 return Result;
1836}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001837
Douglas Gregor5352ac02010-01-28 00:27:43 +00001838CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1839 if (begin.ptr_data[0] != end.ptr_data[0] ||
1840 begin.ptr_data[1] != end.ptr_data[1])
1841 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001842
1843 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001844 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001845 return Result;
1846}
1847
Douglas Gregor46766dc2010-01-26 19:19:08 +00001848void clang_getInstantiationLocation(CXSourceLocation location,
1849 CXFile *file,
1850 unsigned *line,
1851 unsigned *column,
1852 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001853 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1854
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001855 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001856 if (file)
1857 *file = 0;
1858 if (line)
1859 *line = 0;
1860 if (column)
1861 *column = 0;
1862 if (offset)
1863 *offset = 0;
1864 return;
1865 }
1866
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001867 const SourceManager &SM =
1868 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001869 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001870
1871 if (file)
1872 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1873 if (line)
1874 *line = SM.getInstantiationLineNumber(InstLoc);
1875 if (column)
1876 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001877 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001878 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001879}
1880
Douglas Gregor1db19de2010-01-19 21:36:55 +00001881CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001882 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001883 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001884 return Result;
1885}
1886
1887CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001888 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001889 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001890 return Result;
1891}
1892
Douglas Gregorb9790342010-01-22 21:44:22 +00001893} // end: extern "C"
1894
Douglas Gregor1db19de2010-01-19 21:36:55 +00001895//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001896// CXFile Operations.
1897//===----------------------------------------------------------------------===//
1898
1899extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001900CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001901 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001902 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001903
Steve Naroff88145032009-10-27 14:35:18 +00001904 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001905 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001906}
1907
1908time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001909 if (!SFile)
1910 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001911
Steve Naroff88145032009-10-27 14:35:18 +00001912 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1913 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001914}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001915
Douglas Gregorb9790342010-01-22 21:44:22 +00001916CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1917 if (!tu)
1918 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001919
Douglas Gregorb9790342010-01-22 21:44:22 +00001920 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001921
Douglas Gregorb9790342010-01-22 21:44:22 +00001922 FileManager &FMgr = CXXUnit->getFileManager();
1923 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1924 return const_cast<FileEntry *>(File);
1925}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001926
Ted Kremenekfb480492010-01-13 21:46:36 +00001927} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001928
Ted Kremenekfb480492010-01-13 21:46:36 +00001929//===----------------------------------------------------------------------===//
1930// CXCursor Operations.
1931//===----------------------------------------------------------------------===//
1932
Ted Kremenekfb480492010-01-13 21:46:36 +00001933static Decl *getDeclFromExpr(Stmt *E) {
1934 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1935 return RefExpr->getDecl();
1936 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1937 return ME->getMemberDecl();
1938 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1939 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001940
Ted Kremenekfb480492010-01-13 21:46:36 +00001941 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1942 return getDeclFromExpr(CE->getCallee());
1943 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1944 return getDeclFromExpr(CE->getSubExpr());
1945 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1946 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001947
Ted Kremenekfb480492010-01-13 21:46:36 +00001948 return 0;
1949}
1950
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001951static SourceLocation getLocationFromExpr(Expr *E) {
1952 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1953 return /*FIXME:*/Msg->getLeftLoc();
1954 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1955 return DRE->getLocation();
1956 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1957 return Member->getMemberLoc();
1958 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1959 return Ivar->getLocation();
1960 return E->getLocStart();
1961}
1962
Ted Kremenekfb480492010-01-13 21:46:36 +00001963extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001964
1965unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001966 CXCursorVisitor visitor,
1967 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001968 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001969
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001970 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1971 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00001972 return CursorVis.VisitChildren(parent);
1973}
1974
Douglas Gregor78205d42010-01-20 21:45:58 +00001975static CXString getDeclSpelling(Decl *D) {
1976 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1977 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001978 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001979
Douglas Gregor78205d42010-01-20 21:45:58 +00001980 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001981 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001982
Douglas Gregor78205d42010-01-20 21:45:58 +00001983 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1984 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1985 // and returns different names. NamedDecl returns the class name and
1986 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001987 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001988
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00001989 llvm::SmallString<1024> S;
1990 llvm::raw_svector_ostream os(S);
1991 ND->printName(os);
1992
1993 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00001994}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001995
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001996CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001997 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001998 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001999
Steve Narofff334b4e2009-09-02 18:26:48 +00002000 if (clang_isReference(C.kind)) {
2001 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002002 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002003 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002004 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002005 }
2006 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002007 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002008 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002009 }
2010 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002011 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002012 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002013 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002014 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002015 case CXCursor_CXXBaseSpecifier: {
2016 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2017 return createCXString(B->getType().getAsString());
2018 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002019 case CXCursor_TypeRef: {
2020 TypeDecl *Type = getCursorTypeRef(C).first;
2021 assert(Type && "Missing type decl");
2022
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002023 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2024 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002025 }
2026
Daniel Dunbaracca7252009-11-30 20:42:49 +00002027 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002028 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002029 }
2030 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002031
2032 if (clang_isExpression(C.kind)) {
2033 Decl *D = getDeclFromExpr(getCursorExpr(C));
2034 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002035 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002036 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002037 }
2038
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002039 if (C.kind == CXCursor_MacroInstantiation)
2040 return createCXString(getCursorMacroInstantiation(C)->getName()
2041 ->getNameStart());
2042
Douglas Gregor572feb22010-03-18 18:04:21 +00002043 if (C.kind == CXCursor_MacroDefinition)
2044 return createCXString(getCursorMacroDefinition(C)->getName()
2045 ->getNameStart());
2046
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002047 if (clang_isDeclaration(C.kind))
2048 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002049
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002050 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002051}
2052
Ted Kremeneke68fff62010-02-17 00:41:32 +00002053CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002054 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002055 case CXCursor_FunctionDecl:
2056 return createCXString("FunctionDecl");
2057 case CXCursor_TypedefDecl:
2058 return createCXString("TypedefDecl");
2059 case CXCursor_EnumDecl:
2060 return createCXString("EnumDecl");
2061 case CXCursor_EnumConstantDecl:
2062 return createCXString("EnumConstantDecl");
2063 case CXCursor_StructDecl:
2064 return createCXString("StructDecl");
2065 case CXCursor_UnionDecl:
2066 return createCXString("UnionDecl");
2067 case CXCursor_ClassDecl:
2068 return createCXString("ClassDecl");
2069 case CXCursor_FieldDecl:
2070 return createCXString("FieldDecl");
2071 case CXCursor_VarDecl:
2072 return createCXString("VarDecl");
2073 case CXCursor_ParmDecl:
2074 return createCXString("ParmDecl");
2075 case CXCursor_ObjCInterfaceDecl:
2076 return createCXString("ObjCInterfaceDecl");
2077 case CXCursor_ObjCCategoryDecl:
2078 return createCXString("ObjCCategoryDecl");
2079 case CXCursor_ObjCProtocolDecl:
2080 return createCXString("ObjCProtocolDecl");
2081 case CXCursor_ObjCPropertyDecl:
2082 return createCXString("ObjCPropertyDecl");
2083 case CXCursor_ObjCIvarDecl:
2084 return createCXString("ObjCIvarDecl");
2085 case CXCursor_ObjCInstanceMethodDecl:
2086 return createCXString("ObjCInstanceMethodDecl");
2087 case CXCursor_ObjCClassMethodDecl:
2088 return createCXString("ObjCClassMethodDecl");
2089 case CXCursor_ObjCImplementationDecl:
2090 return createCXString("ObjCImplementationDecl");
2091 case CXCursor_ObjCCategoryImplDecl:
2092 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002093 case CXCursor_CXXMethod:
2094 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002095 case CXCursor_UnexposedDecl:
2096 return createCXString("UnexposedDecl");
2097 case CXCursor_ObjCSuperClassRef:
2098 return createCXString("ObjCSuperClassRef");
2099 case CXCursor_ObjCProtocolRef:
2100 return createCXString("ObjCProtocolRef");
2101 case CXCursor_ObjCClassRef:
2102 return createCXString("ObjCClassRef");
2103 case CXCursor_TypeRef:
2104 return createCXString("TypeRef");
2105 case CXCursor_UnexposedExpr:
2106 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002107 case CXCursor_BlockExpr:
2108 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002109 case CXCursor_DeclRefExpr:
2110 return createCXString("DeclRefExpr");
2111 case CXCursor_MemberRefExpr:
2112 return createCXString("MemberRefExpr");
2113 case CXCursor_CallExpr:
2114 return createCXString("CallExpr");
2115 case CXCursor_ObjCMessageExpr:
2116 return createCXString("ObjCMessageExpr");
2117 case CXCursor_UnexposedStmt:
2118 return createCXString("UnexposedStmt");
2119 case CXCursor_InvalidFile:
2120 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002121 case CXCursor_InvalidCode:
2122 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002123 case CXCursor_NoDeclFound:
2124 return createCXString("NoDeclFound");
2125 case CXCursor_NotImplemented:
2126 return createCXString("NotImplemented");
2127 case CXCursor_TranslationUnit:
2128 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002129 case CXCursor_UnexposedAttr:
2130 return createCXString("UnexposedAttr");
2131 case CXCursor_IBActionAttr:
2132 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002133 case CXCursor_IBOutletAttr:
2134 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002135 case CXCursor_IBOutletCollectionAttr:
2136 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002137 case CXCursor_PreprocessingDirective:
2138 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002139 case CXCursor_MacroDefinition:
2140 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002141 case CXCursor_MacroInstantiation:
2142 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002143 case CXCursor_Namespace:
2144 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002145 case CXCursor_LinkageSpec:
2146 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002147 case CXCursor_CXXBaseSpecifier:
2148 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002149 case CXCursor_Constructor:
2150 return createCXString("CXXConstructor");
2151 case CXCursor_Destructor:
2152 return createCXString("CXXDestructor");
2153 case CXCursor_ConversionFunction:
2154 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002155 case CXCursor_TemplateTypeParameter:
2156 return createCXString("TemplateTypeParameter");
2157 case CXCursor_NonTypeTemplateParameter:
2158 return createCXString("NonTypeTemplateParameter");
2159 case CXCursor_TemplateTemplateParameter:
2160 return createCXString("TemplateTemplateParameter");
2161 case CXCursor_FunctionTemplate:
2162 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002163 case CXCursor_ClassTemplate:
2164 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002165 case CXCursor_ClassTemplatePartialSpecialization:
2166 return createCXString("ClassTemplatePartialSpecialization");
Steve Naroff89922f82009-08-31 00:59:03 +00002167 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002168
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002169 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002170 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002171}
Steve Naroff89922f82009-08-31 00:59:03 +00002172
Ted Kremeneke68fff62010-02-17 00:41:32 +00002173enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2174 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002175 CXClientData client_data) {
2176 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2177 *BestCursor = cursor;
2178 return CXChildVisit_Recurse;
2179}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002180
Douglas Gregorb9790342010-01-22 21:44:22 +00002181CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2182 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002183 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002184
Douglas Gregorb9790342010-01-22 21:44:22 +00002185 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002186 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2187
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002188 // Translate the given source location to make it point at the beginning of
2189 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002190 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002191
2192 // Guard against an invalid SourceLocation, or we may assert in one
2193 // of the following calls.
2194 if (SLoc.isInvalid())
2195 return clang_getNullCursor();
2196
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002197 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2198 CXXUnit->getASTContext().getLangOptions());
2199
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002200 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2201 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002202 // FIXME: Would be great to have a "hint" cursor, then walk from that
2203 // hint cursor upward until we find a cursor whose source range encloses
2204 // the region of interest, rather than starting from the translation unit.
2205 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002206 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002207 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002208 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002209 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002210 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002211}
2212
Ted Kremenek73885552009-11-17 19:28:59 +00002213CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002214 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002215}
2216
2217unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002218 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002219}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002220
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002221unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002222 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2223}
2224
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002225unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002226 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2227}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002228
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002229unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002230 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2231}
2232
Douglas Gregor97b98722010-01-19 23:20:36 +00002233unsigned clang_isExpression(enum CXCursorKind K) {
2234 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2235}
2236
2237unsigned clang_isStatement(enum CXCursorKind K) {
2238 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2239}
2240
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002241unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2242 return K == CXCursor_TranslationUnit;
2243}
2244
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002245unsigned clang_isPreprocessing(enum CXCursorKind K) {
2246 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2247}
2248
Ted Kremenekad6eff62010-03-08 21:17:29 +00002249unsigned clang_isUnexposed(enum CXCursorKind K) {
2250 switch (K) {
2251 case CXCursor_UnexposedDecl:
2252 case CXCursor_UnexposedExpr:
2253 case CXCursor_UnexposedStmt:
2254 case CXCursor_UnexposedAttr:
2255 return true;
2256 default:
2257 return false;
2258 }
2259}
2260
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002261CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002262 return C.kind;
2263}
2264
Douglas Gregor98258af2010-01-18 22:46:11 +00002265CXSourceLocation clang_getCursorLocation(CXCursor C) {
2266 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002267 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002268 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002269 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2270 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002271 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002272 }
2273
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002274 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002275 std::pair<ObjCProtocolDecl *, SourceLocation> P
2276 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002277 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002278 }
2279
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002280 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002281 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2282 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002283 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002284 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002285
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002286 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002287 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002288 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002289 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002290
2291 case CXCursor_CXXBaseSpecifier: {
2292 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2293 return clang_getNullLocation();
2294 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002295
Douglas Gregorf46034a2010-01-18 23:41:10 +00002296 default:
2297 // FIXME: Need a way to enumerate all non-reference cases.
2298 llvm_unreachable("Missed a reference kind");
2299 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002300 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002301
2302 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002303 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002304 getLocationFromExpr(getCursorExpr(C)));
2305
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002306 if (C.kind == CXCursor_PreprocessingDirective) {
2307 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2308 return cxloc::translateSourceLocation(getCursorContext(C), L);
2309 }
Douglas Gregor48072312010-03-18 15:23:44 +00002310
2311 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002312 SourceLocation L
2313 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002314 return cxloc::translateSourceLocation(getCursorContext(C), L);
2315 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002316
2317 if (C.kind == CXCursor_MacroDefinition) {
2318 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2319 return cxloc::translateSourceLocation(getCursorContext(C), L);
2320 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002321
Ted Kremenek9a700d22010-05-12 06:16:13 +00002322 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002323 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002324
Douglas Gregorf46034a2010-01-18 23:41:10 +00002325 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002326 SourceLocation Loc = D->getLocation();
2327 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2328 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002329 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002330}
Douglas Gregora7bde202010-01-19 00:34:46 +00002331
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002332} // end extern "C"
2333
2334static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002335 if (clang_isReference(C.kind)) {
2336 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002337 case CXCursor_ObjCSuperClassRef:
2338 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002339
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002340 case CXCursor_ObjCProtocolRef:
2341 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002342
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002343 case CXCursor_ObjCClassRef:
2344 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002345
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002346 case CXCursor_TypeRef:
2347 return getCursorTypeRef(C).second;
Ted Kremenek3064ef92010-08-27 21:34:58 +00002348
2349 case CXCursor_CXXBaseSpecifier:
2350 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2351 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002352
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002353 default:
2354 // FIXME: Need a way to enumerate all non-reference cases.
2355 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002356 }
2357 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002358
2359 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002360 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002361
2362 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002363 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002364
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002365 if (C.kind == CXCursor_PreprocessingDirective)
2366 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002367
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002368 if (C.kind == CXCursor_MacroInstantiation)
2369 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002370
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002371 if (C.kind == CXCursor_MacroDefinition)
2372 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002373
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002374 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2375 return getCursorDecl(C)->getSourceRange();
2376
2377 return SourceRange();
2378}
2379
2380extern "C" {
2381
2382CXSourceRange clang_getCursorExtent(CXCursor C) {
2383 SourceRange R = getRawCursorExtent(C);
2384 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002385 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002386
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002387 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002388}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002389
2390CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002391 if (clang_isInvalid(C.kind))
2392 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002393
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002394 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002395 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002396 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002397
Douglas Gregor97b98722010-01-19 23:20:36 +00002398 if (clang_isExpression(C.kind)) {
2399 Decl *D = getDeclFromExpr(getCursorExpr(C));
2400 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002401 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002402 return clang_getNullCursor();
2403 }
2404
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002405 if (C.kind == CXCursor_MacroInstantiation) {
2406 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2407 return MakeMacroDefinitionCursor(Def, CXXUnit);
2408 }
2409
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002410 if (!clang_isReference(C.kind))
2411 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002412
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002413 switch (C.kind) {
2414 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002415 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002416
2417 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002418 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002419
2420 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002421 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002422
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002423 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002424 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenek3064ef92010-08-27 21:34:58 +00002425
2426 case CXCursor_CXXBaseSpecifier: {
2427 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2428 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2429 CXXUnit));
2430 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002431
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002432 default:
2433 // We would prefer to enumerate all non-reference cursor kinds here.
2434 llvm_unreachable("Unhandled reference cursor kind");
2435 break;
2436 }
2437 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002438
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002439 return clang_getNullCursor();
2440}
2441
Douglas Gregorb6998662010-01-19 19:34:47 +00002442CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002443 if (clang_isInvalid(C.kind))
2444 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002445
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002446 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002447
Douglas Gregorb6998662010-01-19 19:34:47 +00002448 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002449 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002450 C = clang_getCursorReferenced(C);
2451 WasReference = true;
2452 }
2453
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002454 if (C.kind == CXCursor_MacroInstantiation)
2455 return clang_getCursorReferenced(C);
2456
Douglas Gregorb6998662010-01-19 19:34:47 +00002457 if (!clang_isDeclaration(C.kind))
2458 return clang_getNullCursor();
2459
2460 Decl *D = getCursorDecl(C);
2461 if (!D)
2462 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002463
Douglas Gregorb6998662010-01-19 19:34:47 +00002464 switch (D->getKind()) {
2465 // Declaration kinds that don't really separate the notions of
2466 // declaration and definition.
2467 case Decl::Namespace:
2468 case Decl::Typedef:
2469 case Decl::TemplateTypeParm:
2470 case Decl::EnumConstant:
2471 case Decl::Field:
2472 case Decl::ObjCIvar:
2473 case Decl::ObjCAtDefsField:
2474 case Decl::ImplicitParam:
2475 case Decl::ParmVar:
2476 case Decl::NonTypeTemplateParm:
2477 case Decl::TemplateTemplateParm:
2478 case Decl::ObjCCategoryImpl:
2479 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002480 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002481 case Decl::LinkageSpec:
2482 case Decl::ObjCPropertyImpl:
2483 case Decl::FileScopeAsm:
2484 case Decl::StaticAssert:
2485 case Decl::Block:
2486 return C;
2487
2488 // Declaration kinds that don't make any sense here, but are
2489 // nonetheless harmless.
2490 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002491 break;
2492
2493 // Declaration kinds for which the definition is not resolvable.
2494 case Decl::UnresolvedUsingTypename:
2495 case Decl::UnresolvedUsingValue:
2496 break;
2497
2498 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002499 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2500 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002501
2502 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002503 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002504
2505 case Decl::Enum:
2506 case Decl::Record:
2507 case Decl::CXXRecord:
2508 case Decl::ClassTemplateSpecialization:
2509 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002510 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002511 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002512 return clang_getNullCursor();
2513
2514 case Decl::Function:
2515 case Decl::CXXMethod:
2516 case Decl::CXXConstructor:
2517 case Decl::CXXDestructor:
2518 case Decl::CXXConversion: {
2519 const FunctionDecl *Def = 0;
2520 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002521 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002522 return clang_getNullCursor();
2523 }
2524
2525 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002526 // Ask the variable if it has a definition.
2527 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2528 return MakeCXCursor(Def, CXXUnit);
2529 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002530 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002531
Douglas Gregorb6998662010-01-19 19:34:47 +00002532 case Decl::FunctionTemplate: {
2533 const FunctionDecl *Def = 0;
2534 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002535 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002536 return clang_getNullCursor();
2537 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002538
Douglas Gregorb6998662010-01-19 19:34:47 +00002539 case Decl::ClassTemplate: {
2540 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002541 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00002542 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002543 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002544 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002545 return clang_getNullCursor();
2546 }
2547
2548 case Decl::Using: {
2549 UsingDecl *Using = cast<UsingDecl>(D);
2550 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002551 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2552 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002553 S != SEnd; ++S) {
2554 if (Def != clang_getNullCursor()) {
2555 // FIXME: We have no way to return multiple results.
2556 return clang_getNullCursor();
2557 }
2558
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002559 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002560 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002561 }
2562
2563 return Def;
2564 }
2565
2566 case Decl::UsingShadow:
2567 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002568 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002569 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002570
2571 case Decl::ObjCMethod: {
2572 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2573 if (Method->isThisDeclarationADefinition())
2574 return C;
2575
2576 // Dig out the method definition in the associated
2577 // @implementation, if we have it.
2578 // FIXME: The ASTs should make finding the definition easier.
2579 if (ObjCInterfaceDecl *Class
2580 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2581 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2582 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2583 Method->isInstanceMethod()))
2584 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002585 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002586
2587 return clang_getNullCursor();
2588 }
2589
2590 case Decl::ObjCCategory:
2591 if (ObjCCategoryImplDecl *Impl
2592 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002593 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002594 return clang_getNullCursor();
2595
2596 case Decl::ObjCProtocol:
2597 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2598 return C;
2599 return clang_getNullCursor();
2600
2601 case Decl::ObjCInterface:
2602 // There are two notions of a "definition" for an Objective-C
2603 // class: the interface and its implementation. When we resolved a
2604 // reference to an Objective-C class, produce the @interface as
2605 // the definition; when we were provided with the interface,
2606 // produce the @implementation as the definition.
2607 if (WasReference) {
2608 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2609 return C;
2610 } else if (ObjCImplementationDecl *Impl
2611 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002612 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002613 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002614
Douglas Gregorb6998662010-01-19 19:34:47 +00002615 case Decl::ObjCProperty:
2616 // FIXME: We don't really know where to find the
2617 // ObjCPropertyImplDecls that implement this property.
2618 return clang_getNullCursor();
2619
2620 case Decl::ObjCCompatibleAlias:
2621 if (ObjCInterfaceDecl *Class
2622 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2623 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002624 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002625
Douglas Gregorb6998662010-01-19 19:34:47 +00002626 return clang_getNullCursor();
2627
2628 case Decl::ObjCForwardProtocol: {
2629 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2630 if (Forward->protocol_size() == 1)
2631 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002632 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002633 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002634
2635 // FIXME: Cannot return multiple definitions.
2636 return clang_getNullCursor();
2637 }
2638
2639 case Decl::ObjCClass: {
2640 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2641 if (Class->size() == 1) {
2642 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2643 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002644 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002645 return clang_getNullCursor();
2646 }
2647
2648 // FIXME: Cannot return multiple definitions.
2649 return clang_getNullCursor();
2650 }
2651
2652 case Decl::Friend:
2653 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002654 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002655 return clang_getNullCursor();
2656
2657 case Decl::FriendTemplate:
2658 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002659 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002660 return clang_getNullCursor();
2661 }
2662
2663 return clang_getNullCursor();
2664}
2665
2666unsigned clang_isCursorDefinition(CXCursor C) {
2667 if (!clang_isDeclaration(C.kind))
2668 return 0;
2669
2670 return clang_getCursorDefinition(C) == C;
2671}
2672
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002673void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002674 const char **startBuf,
2675 const char **endBuf,
2676 unsigned *startLine,
2677 unsigned *startColumn,
2678 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002679 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002680 assert(getCursorDecl(C) && "CXCursor has null decl");
2681 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002682 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2683 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002684
Steve Naroff4ade6d62009-09-23 17:52:52 +00002685 SourceManager &SM = FD->getASTContext().getSourceManager();
2686 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2687 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2688 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2689 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2690 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2691 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2692}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002693
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002694void clang_enableStackTraces(void) {
2695 llvm::sys::PrintStackTraceOnErrorSignal();
2696}
2697
Ted Kremenekfb480492010-01-13 21:46:36 +00002698} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002699
Ted Kremenekfb480492010-01-13 21:46:36 +00002700//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002701// Token-based Operations.
2702//===----------------------------------------------------------------------===//
2703
2704/* CXToken layout:
2705 * int_data[0]: a CXTokenKind
2706 * int_data[1]: starting token location
2707 * int_data[2]: token length
2708 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002709 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002710 * otherwise unused.
2711 */
2712extern "C" {
2713
2714CXTokenKind clang_getTokenKind(CXToken CXTok) {
2715 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2716}
2717
2718CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2719 switch (clang_getTokenKind(CXTok)) {
2720 case CXToken_Identifier:
2721 case CXToken_Keyword:
2722 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002723 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2724 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002725
2726 case CXToken_Literal: {
2727 // We have stashed the starting pointer in the ptr_data field. Use it.
2728 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002729 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002730 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002731
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002732 case CXToken_Punctuation:
2733 case CXToken_Comment:
2734 break;
2735 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002736
2737 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002738 // deconstructing the source location.
2739 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2740 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002741 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002742
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002743 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2744 std::pair<FileID, unsigned> LocInfo
2745 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002746 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002747 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002748 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2749 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002750 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002751
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002752 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002753}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002754
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002755CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2756 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2757 if (!CXXUnit)
2758 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002759
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002760 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2761 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2762}
2763
2764CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2765 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002766 if (!CXXUnit)
2767 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002768
2769 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002770 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2771}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002772
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002773void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2774 CXToken **Tokens, unsigned *NumTokens) {
2775 if (Tokens)
2776 *Tokens = 0;
2777 if (NumTokens)
2778 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002779
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002780 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2781 if (!CXXUnit || !Tokens || !NumTokens)
2782 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002783
Douglas Gregorbdf60622010-03-05 21:16:25 +00002784 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2785
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002786 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002787 if (R.isInvalid())
2788 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002789
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002790 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2791 std::pair<FileID, unsigned> BeginLocInfo
2792 = SourceMgr.getDecomposedLoc(R.getBegin());
2793 std::pair<FileID, unsigned> EndLocInfo
2794 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002795
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002796 // Cannot tokenize across files.
2797 if (BeginLocInfo.first != EndLocInfo.first)
2798 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002799
2800 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002801 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002802 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002803 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002804 if (Invalid)
2805 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002806
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002807 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2808 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002809 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002810 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002811
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002812 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002813 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002814 llvm::SmallVector<CXToken, 32> CXTokens;
2815 Token Tok;
2816 do {
2817 // Lex the next token
2818 Lex.LexFromRawLexer(Tok);
2819 if (Tok.is(tok::eof))
2820 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002821
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002822 // Initialize the CXToken.
2823 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002824
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002825 // - Common fields
2826 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2827 CXTok.int_data[2] = Tok.getLength();
2828 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002829
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002830 // - Kind-specific fields
2831 if (Tok.isLiteral()) {
2832 CXTok.int_data[0] = CXToken_Literal;
2833 CXTok.ptr_data = (void *)Tok.getLiteralData();
2834 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002835 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002836 std::pair<FileID, unsigned> LocInfo
2837 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002838 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002839 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002840 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2841 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002842 return;
2843
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002844 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002845 IdentifierInfo *II
2846 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002847
2848 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2849 CXTok.int_data[0] = CXToken_Keyword;
2850 }
2851 else {
2852 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2853 CXToken_Identifier
2854 : CXToken_Keyword;
2855 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002856 CXTok.ptr_data = II;
2857 } else if (Tok.is(tok::comment)) {
2858 CXTok.int_data[0] = CXToken_Comment;
2859 CXTok.ptr_data = 0;
2860 } else {
2861 CXTok.int_data[0] = CXToken_Punctuation;
2862 CXTok.ptr_data = 0;
2863 }
2864 CXTokens.push_back(CXTok);
2865 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002866
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002867 if (CXTokens.empty())
2868 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002869
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002870 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2871 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2872 *NumTokens = CXTokens.size();
2873}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002874
Ted Kremenek6db61092010-05-05 00:55:15 +00002875void clang_disposeTokens(CXTranslationUnit TU,
2876 CXToken *Tokens, unsigned NumTokens) {
2877 free(Tokens);
2878}
2879
2880} // end: extern "C"
2881
2882//===----------------------------------------------------------------------===//
2883// Token annotation APIs.
2884//===----------------------------------------------------------------------===//
2885
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002886typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002887static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2888 CXCursor parent,
2889 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002890namespace {
2891class AnnotateTokensWorker {
2892 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002893 CXToken *Tokens;
2894 CXCursor *Cursors;
2895 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002896 unsigned TokIdx;
2897 CursorVisitor AnnotateVis;
2898 SourceManager &SrcMgr;
2899
2900 bool MoreTokens() const { return TokIdx < NumTokens; }
2901 unsigned NextToken() const { return TokIdx; }
2902 void AdvanceToken() { ++TokIdx; }
2903 SourceLocation GetTokenLoc(unsigned tokI) {
2904 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2905 }
2906
Ted Kremenek6db61092010-05-05 00:55:15 +00002907public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002908 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002909 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2910 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002911 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002912 NumTokens(numTokens), TokIdx(0),
2913 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2914 Decl::MaxPCHLevel, RegionOfInterest),
2915 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002916
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002917 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002918 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002919 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002920};
2921}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002922
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002923void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2924 // Walk the AST within the region of interest, annotating tokens
2925 // along the way.
2926 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002927
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002928 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2929 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2930 if (Pos != Annotated.end())
2931 Cursors[I] = Pos->second;
2932 }
2933
2934 // Finish up annotating any tokens left.
2935 if (!MoreTokens())
2936 return;
2937
2938 const CXCursor &C = clang_getNullCursor();
2939 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2940 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2941 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002942 }
2943}
2944
Ted Kremenek6db61092010-05-05 00:55:15 +00002945enum CXChildVisitResult
2946AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002947 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2948 // We can always annotate a preprocessing directive/macro instantiation.
2949 if (clang_isPreprocessing(cursor.kind)) {
2950 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002951 return CXChildVisit_Recurse;
2952 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002953
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002954 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00002955
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002956 if (cursorRange.isInvalid())
2957 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00002958
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002959 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2960
Ted Kremeneka333c662010-05-12 05:29:33 +00002961 // Adjust the annotated range based specific declarations.
2962 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2963 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00002964 Decl *D = cxcursor::getCursorDecl(cursor);
2965 // Don't visit synthesized ObjC methods, since they have no syntatic
2966 // representation in the source.
2967 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2968 if (MD->isSynthesized())
2969 return CXChildVisit_Continue;
2970 }
2971 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00002972 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2973 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002974 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00002975 if (TLoc.isValid() &&
2976 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00002977 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00002978 }
2979 }
2980 }
2981
Ted Kremenek3f404602010-08-14 01:14:06 +00002982 // If the location of the cursor occurs within a macro instantiation, record
2983 // the spelling location of the cursor in our annotation map. We can then
2984 // paper over the token labelings during a post-processing step to try and
2985 // get cursor mappings for tokens that are the *arguments* of a macro
2986 // instantiation.
2987 if (L.isMacroID()) {
2988 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
2989 // Only invalidate the old annotation if it isn't part of a preprocessing
2990 // directive. Here we assume that the default construction of CXCursor
2991 // results in CXCursor.kind being an initialized value (i.e., 0). If
2992 // this isn't the case, we can fix by doing lookup + insertion.
2993
2994 CXCursor &oldC = Annotated[rawEncoding];
2995 if (!clang_isPreprocessing(oldC.kind))
2996 oldC = cursor;
2997 }
2998
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002999 const enum CXCursorKind K = clang_getCursorKind(parent);
3000 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003001 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3002 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003003
3004 while (MoreTokens()) {
3005 const unsigned I = NextToken();
3006 SourceLocation TokLoc = GetTokenLoc(I);
3007 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3008 case RangeBefore:
3009 Cursors[I] = updateC;
3010 AdvanceToken();
3011 continue;
3012 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003013 case RangeOverlap:
3014 break;
3015 }
3016 break;
3017 }
3018
3019 // Visit children to get their cursor information.
3020 const unsigned BeforeChildren = NextToken();
3021 VisitChildren(cursor);
3022 const unsigned AfterChildren = NextToken();
3023
3024 // Adjust 'Last' to the last token within the extent of the cursor.
3025 while (MoreTokens()) {
3026 const unsigned I = NextToken();
3027 SourceLocation TokLoc = GetTokenLoc(I);
3028 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3029 case RangeBefore:
3030 assert(0 && "Infeasible");
3031 case RangeAfter:
3032 break;
3033 case RangeOverlap:
3034 Cursors[I] = updateC;
3035 AdvanceToken();
3036 continue;
3037 }
3038 break;
3039 }
3040 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003041
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003042 // Scan the tokens that are at the beginning of the cursor, but are not
3043 // capture by the child cursors.
3044
3045 // For AST elements within macros, rely on a post-annotate pass to
3046 // to correctly annotate the tokens with cursors. Otherwise we can
3047 // get confusing results of having tokens that map to cursors that really
3048 // are expanded by an instantiation.
3049 if (L.isMacroID())
3050 cursor = clang_getNullCursor();
3051
3052 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3053 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3054 break;
3055 Cursors[I] = cursor;
3056 }
3057 // Scan the tokens that are at the end of the cursor, but are not captured
3058 // but the child cursors.
3059 for (unsigned I = AfterChildren; I != Last; ++I)
3060 Cursors[I] = cursor;
3061
3062 TokIdx = Last;
3063 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003064}
3065
Ted Kremenek6db61092010-05-05 00:55:15 +00003066static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3067 CXCursor parent,
3068 CXClientData client_data) {
3069 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3070}
3071
3072extern "C" {
3073
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003074void clang_annotateTokens(CXTranslationUnit TU,
3075 CXToken *Tokens, unsigned NumTokens,
3076 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003077
3078 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003079 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003080
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003081 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003082 if (!CXXUnit) {
3083 // Any token we don't specifically annotate will have a NULL cursor.
3084 const CXCursor &C = clang_getNullCursor();
3085 for (unsigned I = 0; I != NumTokens; ++I)
3086 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003087 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003088 }
3089
Douglas Gregorbdf60622010-03-05 21:16:25 +00003090 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003091
Douglas Gregor0396f462010-03-19 05:22:59 +00003092 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003093 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003094 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3095 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003096 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3097 clang_getTokenLocation(TU,
3098 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003099
Douglas Gregor0396f462010-03-19 05:22:59 +00003100 // A mapping from the source locations found when re-lexing or traversing the
3101 // region of interest to the corresponding cursors.
3102 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003103
3104 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003105 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003106 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3107 std::pair<FileID, unsigned> BeginLocInfo
3108 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3109 std::pair<FileID, unsigned> EndLocInfo
3110 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003111
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003112 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003113 bool Invalid = false;
3114 if (BeginLocInfo.first == EndLocInfo.first &&
3115 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3116 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003117 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3118 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003119 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003120 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003121 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003122
3123 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003124 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003125 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003126 Token Tok;
3127 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003128
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003129 reprocess:
3130 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3131 // We have found a preprocessing directive. Gobble it up so that we
3132 // don't see it while preprocessing these tokens later, but keep track of
3133 // all of the token locations inside this preprocessing directive so that
3134 // we can annotate them appropriately.
3135 //
3136 // FIXME: Some simple tests here could identify macro definitions and
3137 // #undefs, to provide specific cursor kinds for those.
3138 std::vector<SourceLocation> Locations;
3139 do {
3140 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003141 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003142 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003143
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003144 using namespace cxcursor;
3145 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003146 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3147 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003148 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003149 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3150 Annotated[Locations[I].getRawEncoding()] = Cursor;
3151 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003152
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003153 if (Tok.isAtStartOfLine())
3154 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003155
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003156 continue;
3157 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003158
Douglas Gregor48072312010-03-18 15:23:44 +00003159 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003160 break;
3161 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003162 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003163
Douglas Gregor0396f462010-03-19 05:22:59 +00003164 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003165 // a specific cursor.
3166 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3167 CXXUnit, RegionOfInterest);
3168 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003169}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003170} // end: extern "C"
3171
3172//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003173// Operations for querying linkage of a cursor.
3174//===----------------------------------------------------------------------===//
3175
3176extern "C" {
3177CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003178 if (!clang_isDeclaration(cursor.kind))
3179 return CXLinkage_Invalid;
3180
Ted Kremenek16b42592010-03-03 06:36:57 +00003181 Decl *D = cxcursor::getCursorDecl(cursor);
3182 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3183 switch (ND->getLinkage()) {
3184 case NoLinkage: return CXLinkage_NoLinkage;
3185 case InternalLinkage: return CXLinkage_Internal;
3186 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3187 case ExternalLinkage: return CXLinkage_External;
3188 };
3189
3190 return CXLinkage_Invalid;
3191}
3192} // end: extern "C"
3193
3194//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003195// Operations for querying language of a cursor.
3196//===----------------------------------------------------------------------===//
3197
3198static CXLanguageKind getDeclLanguage(const Decl *D) {
3199 switch (D->getKind()) {
3200 default:
3201 break;
3202 case Decl::ImplicitParam:
3203 case Decl::ObjCAtDefsField:
3204 case Decl::ObjCCategory:
3205 case Decl::ObjCCategoryImpl:
3206 case Decl::ObjCClass:
3207 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003208 case Decl::ObjCForwardProtocol:
3209 case Decl::ObjCImplementation:
3210 case Decl::ObjCInterface:
3211 case Decl::ObjCIvar:
3212 case Decl::ObjCMethod:
3213 case Decl::ObjCProperty:
3214 case Decl::ObjCPropertyImpl:
3215 case Decl::ObjCProtocol:
3216 return CXLanguage_ObjC;
3217 case Decl::CXXConstructor:
3218 case Decl::CXXConversion:
3219 case Decl::CXXDestructor:
3220 case Decl::CXXMethod:
3221 case Decl::CXXRecord:
3222 case Decl::ClassTemplate:
3223 case Decl::ClassTemplatePartialSpecialization:
3224 case Decl::ClassTemplateSpecialization:
3225 case Decl::Friend:
3226 case Decl::FriendTemplate:
3227 case Decl::FunctionTemplate:
3228 case Decl::LinkageSpec:
3229 case Decl::Namespace:
3230 case Decl::NamespaceAlias:
3231 case Decl::NonTypeTemplateParm:
3232 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003233 case Decl::TemplateTemplateParm:
3234 case Decl::TemplateTypeParm:
3235 case Decl::UnresolvedUsingTypename:
3236 case Decl::UnresolvedUsingValue:
3237 case Decl::Using:
3238 case Decl::UsingDirective:
3239 case Decl::UsingShadow:
3240 return CXLanguage_CPlusPlus;
3241 }
3242
3243 return CXLanguage_C;
3244}
3245
3246extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003247
3248enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3249 if (clang_isDeclaration(cursor.kind))
3250 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3251 if (D->hasAttr<UnavailableAttr>() ||
3252 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3253 return CXAvailability_Available;
3254
3255 if (D->hasAttr<DeprecatedAttr>())
3256 return CXAvailability_Deprecated;
3257 }
3258
3259 return CXAvailability_Available;
3260}
3261
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003262CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3263 if (clang_isDeclaration(cursor.kind))
3264 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3265
3266 return CXLanguage_Invalid;
3267}
3268} // end: extern "C"
3269
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003270
3271//===----------------------------------------------------------------------===//
3272// C++ AST instrospection.
3273//===----------------------------------------------------------------------===//
3274
3275extern "C" {
3276unsigned clang_CXXMethod_isStatic(CXCursor C) {
3277 if (!clang_isDeclaration(C.kind))
3278 return 0;
3279 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
3280 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003281}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003282
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003283} // end: extern "C"
3284
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003285//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003286// Attribute introspection.
3287//===----------------------------------------------------------------------===//
3288
3289extern "C" {
3290CXType clang_getIBOutletCollectionType(CXCursor C) {
3291 if (C.kind != CXCursor_IBOutletCollectionAttr)
3292 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3293
3294 IBOutletCollectionAttr *A =
3295 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3296
3297 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3298}
3299} // end: extern "C"
3300
3301//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003302// CXString Operations.
3303//===----------------------------------------------------------------------===//
3304
3305extern "C" {
3306const char *clang_getCString(CXString string) {
3307 return string.Spelling;
3308}
3309
3310void clang_disposeString(CXString string) {
3311 if (string.MustFreeString && string.Spelling)
3312 free((void*)string.Spelling);
3313}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003314
Ted Kremenekfb480492010-01-13 21:46:36 +00003315} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003316
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003317namespace clang { namespace cxstring {
3318CXString createCXString(const char *String, bool DupString){
3319 CXString Str;
3320 if (DupString) {
3321 Str.Spelling = strdup(String);
3322 Str.MustFreeString = 1;
3323 } else {
3324 Str.Spelling = String;
3325 Str.MustFreeString = 0;
3326 }
3327 return Str;
3328}
3329
3330CXString createCXString(llvm::StringRef String, bool DupString) {
3331 CXString Result;
3332 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3333 char *Spelling = (char *)malloc(String.size() + 1);
3334 memmove(Spelling, String.data(), String.size());
3335 Spelling[String.size()] = 0;
3336 Result.Spelling = Spelling;
3337 Result.MustFreeString = 1;
3338 } else {
3339 Result.Spelling = String.data();
3340 Result.MustFreeString = 0;
3341 }
3342 return Result;
3343}
3344}}
3345
Ted Kremenek04bb7162010-01-22 22:44:15 +00003346//===----------------------------------------------------------------------===//
3347// Misc. utility functions.
3348//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003349
Ted Kremenek04bb7162010-01-22 22:44:15 +00003350extern "C" {
3351
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003352CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003353 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003354}
3355
3356} // end: extern "C"