blob: 2a7e6e9b0659142281a104f966cc5597b35421b8 [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);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000325 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000326 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
327
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000328 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000329 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000330 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000331 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000332 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
333 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000334 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000335 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000336 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000337 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
338 bool VisitPointerTypeLoc(PointerTypeLoc TL);
339 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
340 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
341 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
342 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000343 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000344 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000345 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000346 // FIXME: Implement visitors here when the unimplemented TypeLocs get
347 // implemented
348 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
349 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000350
Douglas Gregora59e3902010-01-21 23:27:09 +0000351 // Statement visitors
352 bool VisitStmt(Stmt *S);
353 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000354 // FIXME: LabelStmt label?
355 bool VisitIfStmt(IfStmt *S);
356 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000357 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000358 bool VisitWhileStmt(WhileStmt *S);
359 bool VisitForStmt(ForStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000360// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000361
Douglas Gregor336fd812010-01-23 00:40:08 +0000362 // Expression visitors
Douglas Gregor648220e2010-08-10 15:02:34 +0000363 // FIXME: DeclRefExpr with template arguments, nested-name-specifier
364 // FIXME: MemberExpr with template arguments, nested-name-specifier
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000365 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000366 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000367 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000368 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000369 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000370 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000371 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000372 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000373 // FIXME: AddrLabelExpr (once we have cursors for labels)
374 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
375 bool VisitVAArgExpr(VAArgExpr *E);
376 // FIXME: InitListExpr (for the designators)
377 // FIXME: DesignatedInitExpr
Steve Naroff89922f82009-08-31 00:59:03 +0000378};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000379
Ted Kremenekab188932010-01-05 19:32:54 +0000380} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000381
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000382static SourceRange getRawCursorExtent(CXCursor C);
383
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000384RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000385 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
386}
387
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388/// \brief Visit the given cursor and, if requested by the visitor,
389/// its children.
390///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000391/// \param Cursor the cursor to visit.
392///
393/// \param CheckRegionOfInterest if true, then the caller already checked that
394/// this cursor is within the region of interest.
395///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000396/// \returns true if the visitation should be aborted, false if it
397/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000398bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000399 if (clang_isInvalid(Cursor.kind))
400 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000401
Douglas Gregorb1373d02010-01-20 20:59:29 +0000402 if (clang_isDeclaration(Cursor.kind)) {
403 Decl *D = getCursorDecl(Cursor);
404 assert(D && "Invalid declaration cursor");
405 if (D->getPCHLevel() > MaxPCHLevel)
406 return false;
407
408 if (D->isImplicit())
409 return false;
410 }
411
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000412 // If we have a range of interest, and this cursor doesn't intersect with it,
413 // we're done.
414 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000415 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000416 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000417 return false;
418 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000419
Douglas Gregorb1373d02010-01-20 20:59:29 +0000420 switch (Visitor(Cursor, Parent, ClientData)) {
421 case CXChildVisit_Break:
422 return true;
423
424 case CXChildVisit_Continue:
425 return false;
426
427 case CXChildVisit_Recurse:
428 return VisitChildren(Cursor);
429 }
430
Douglas Gregorfd643772010-01-25 16:45:46 +0000431 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000432}
433
Douglas Gregor788f5a12010-03-20 00:41:21 +0000434std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
435CursorVisitor::getPreprocessedEntities() {
436 PreprocessingRecord &PPRec
437 = *TU->getPreprocessor().getPreprocessingRecord();
438
439 bool OnlyLocalDecls
440 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
441
442 // There is no region of interest; we have to walk everything.
443 if (RegionOfInterest.isInvalid())
444 return std::make_pair(PPRec.begin(OnlyLocalDecls),
445 PPRec.end(OnlyLocalDecls));
446
447 // Find the file in which the region of interest lands.
448 SourceManager &SM = TU->getSourceManager();
449 std::pair<FileID, unsigned> Begin
450 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
451 std::pair<FileID, unsigned> End
452 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
453
454 // The region of interest spans files; we have to walk everything.
455 if (Begin.first != End.first)
456 return std::make_pair(PPRec.begin(OnlyLocalDecls),
457 PPRec.end(OnlyLocalDecls));
458
459 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
460 = TU->getPreprocessedEntitiesByFile();
461 if (ByFileMap.empty()) {
462 // Build the mapping from files to sets of preprocessed entities.
463 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
464 EEnd = PPRec.end(OnlyLocalDecls);
465 E != EEnd; ++E) {
466 std::pair<FileID, unsigned> P
467 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
468 ByFileMap[P.first].push_back(*E);
469 }
470 }
471
472 return std::make_pair(ByFileMap[Begin.first].begin(),
473 ByFileMap[Begin.first].end());
474}
475
Douglas Gregorb1373d02010-01-20 20:59:29 +0000476/// \brief Visit the children of the given cursor.
477///
478/// \returns true if the visitation should be aborted, false if it
479/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000480bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000481 if (clang_isReference(Cursor.kind)) {
482 // By definition, references have no children.
483 return false;
484 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000485
486 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000487 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000488 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000489
Douglas Gregorb1373d02010-01-20 20:59:29 +0000490 if (clang_isDeclaration(Cursor.kind)) {
491 Decl *D = getCursorDecl(Cursor);
492 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000493 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000494 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000495
Douglas Gregora59e3902010-01-21 23:27:09 +0000496 if (clang_isStatement(Cursor.kind))
497 return Visit(getCursorStmt(Cursor));
498 if (clang_isExpression(Cursor.kind))
499 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000500
Douglas Gregorb1373d02010-01-20 20:59:29 +0000501 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000502 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000503 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
504 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000505 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
506 TLEnd = CXXUnit->top_level_end();
507 TL != TLEnd; ++TL) {
508 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000509 return true;
510 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000511 } else if (VisitDeclContext(
512 CXXUnit->getASTContext().getTranslationUnitDecl()))
513 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000514
Douglas Gregor0396f462010-03-19 05:22:59 +0000515 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000516 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000517 // FIXME: Once we have the ability to deserialize a preprocessing record,
518 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000519 PreprocessingRecord::iterator E, EEnd;
520 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000521 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
522 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
523 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000524
Douglas Gregor0396f462010-03-19 05:22:59 +0000525 continue;
526 }
527
528 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
529 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
530 return true;
531
532 continue;
533 }
534 }
535 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000536 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000537 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000538
Douglas Gregorb1373d02010-01-20 20:59:29 +0000539 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000540 return false;
541}
542
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000543bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000544 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
545 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000546
Ted Kremenek664cffd2010-07-22 11:30:19 +0000547 if (Stmt *Body = B->getBody())
548 return Visit(MakeCXCursor(Body, StmtParent, TU));
549
550 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000551}
552
Douglas Gregorb1373d02010-01-20 20:59:29 +0000553bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000554 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000555 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000556
Ted Kremenek23173d72010-05-18 21:09:07 +0000557 Decl *D = *I;
558 if (D->getLexicalDeclContext() != DC)
559 continue;
560
561 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000562
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000563 if (RegionOfInterest.isValid()) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000564 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbard52864b2010-02-14 10:02:57 +0000565 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000566 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000567
568 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000569 case RangeBefore:
570 // This declaration comes before the region of interest; skip it.
571 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000572
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000573 case RangeAfter:
574 // This declaration comes after the region of interest; we're done.
575 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000576
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000577 case RangeOverlap:
578 // This declaration overlaps the region of interest; visit it.
579 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000580 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000581 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000582
Daniel Dunbard52864b2010-02-14 10:02:57 +0000583 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 return true;
585 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000586
Douglas Gregorb1373d02010-01-20 20:59:29 +0000587 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000588}
589
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000590bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
591 llvm_unreachable("Translation units are visited directly by Visit()");
592 return false;
593}
594
595bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
596 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
597 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599 return false;
600}
601
602bool CursorVisitor::VisitTagDecl(TagDecl *D) {
603 return VisitDeclContext(D);
604}
605
Douglas Gregor74dbe642010-08-31 19:31:58 +0000606bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
607 ClassTemplatePartialSpecializationDecl *D) {
608 // FIXME: Visit the "outer" template parameter lists on the TagDecl
609 // before visiting these template parameters.
610 if (VisitTemplateParameters(D->getTemplateParameters()))
611 return true;
612
613 // Visit the partial specialization arguments.
614 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
615 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
616 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
617 return true;
618
619 return VisitCXXRecordDecl(D);
620}
621
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000622bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
623 // FIXME: Visit default argument
624 return false;
625}
626
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000627bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
628 if (Expr *Init = D->getInitExpr())
629 return Visit(MakeCXCursor(Init, StmtParent, TU));
630 return false;
631}
632
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000633bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
634 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
635 if (Visit(TSInfo->getTypeLoc()))
636 return true;
637
638 return false;
639}
640
Douglas Gregorb1373d02010-01-20 20:59:29 +0000641bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000642 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
643 // Visit the function declaration's syntactic components in the order
644 // written. This requires a bit of work.
645 TypeLoc TL = TSInfo->getTypeLoc();
646 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
647
648 // If we have a function declared directly (without the use of a typedef),
649 // visit just the return type. Otherwise, just visit the function's type
650 // now.
651 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
652 (!FTL && Visit(TL)))
653 return true;
654
655 // FIXME: Visit the nested-name-specifier, if present.
656
657 // Visit the declaration name.
658 if (VisitDeclarationNameInfo(ND->getNameInfo()))
659 return true;
660
661 // FIXME: Visit explicitly-specified template arguments!
662
663 // Visit the function parameters, if we have a function type.
664 if (FTL && VisitFunctionTypeLoc(*FTL, true))
665 return true;
666
667 // FIXME: Attributes?
668 }
669
Douglas Gregora59e3902010-01-21 23:27:09 +0000670 if (ND->isThisDeclarationADefinition() &&
671 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
672 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000673
Douglas Gregorb1373d02010-01-20 20:59:29 +0000674 return false;
675}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000676
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000677bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
678 if (VisitDeclaratorDecl(D))
679 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000680
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000681 if (Expr *BitWidth = D->getBitWidth())
682 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000683
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000684 return false;
685}
686
687bool CursorVisitor::VisitVarDecl(VarDecl *D) {
688 if (VisitDeclaratorDecl(D))
689 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000690
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000691 if (Expr *Init = D->getInit())
692 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000693
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000694 return false;
695}
696
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000697bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
698 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
699 // before visiting these template parameters.
700 if (VisitTemplateParameters(D->getTemplateParameters()))
701 return true;
702
703 return VisitFunctionDecl(D->getTemplatedDecl());
704}
705
Douglas Gregor39d6f072010-08-31 19:02:00 +0000706bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
707 // FIXME: Visit the "outer" template parameter lists on the TagDecl
708 // before visiting these template parameters.
709 if (VisitTemplateParameters(D->getTemplateParameters()))
710 return true;
711
712 return VisitCXXRecordDecl(D->getTemplatedDecl());
713}
714
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000715bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000716 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
717 if (Visit(TSInfo->getTypeLoc()))
718 return true;
719
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000720 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000721 PEnd = ND->param_end();
722 P != PEnd; ++P) {
723 if (Visit(MakeCXCursor(*P, TU)))
724 return true;
725 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000726
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000727 if (ND->isThisDeclarationADefinition() &&
728 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
729 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000730
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000731 return false;
732}
733
Douglas Gregora59e3902010-01-21 23:27:09 +0000734bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
735 return VisitDeclContext(D);
736}
737
Douglas Gregorb1373d02010-01-20 20:59:29 +0000738bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000739 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
740 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000741 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000742
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000743 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
744 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
745 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000746 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000747 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000748
Douglas Gregora59e3902010-01-21 23:27:09 +0000749 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000750}
751
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000752bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
753 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
754 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
755 E = PID->protocol_end(); I != E; ++I, ++PL)
756 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
757 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000758
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000759 return VisitObjCContainerDecl(PID);
760}
761
Ted Kremenek23173d72010-05-18 21:09:07 +0000762bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCallfc929202010-06-04 22:33:30 +0000763 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
764 return true;
765
Ted Kremenek23173d72010-05-18 21:09:07 +0000766 // FIXME: This implements a workaround with @property declarations also being
767 // installed in the DeclContext for the @interface. Eventually this code
768 // should be removed.
769 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
770 if (!CDecl || !CDecl->IsClassExtension())
771 return false;
772
773 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
774 if (!ID)
775 return false;
776
777 IdentifierInfo *PropertyId = PD->getIdentifier();
778 ObjCPropertyDecl *prevDecl =
779 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
780
781 if (!prevDecl)
782 return false;
783
784 // Visit synthesized methods since they will be skipped when visiting
785 // the @interface.
786 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
787 if (MD->isSynthesized())
788 if (Visit(MakeCXCursor(MD, TU)))
789 return true;
790
791 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
792 if (MD->isSynthesized())
793 if (Visit(MakeCXCursor(MD, TU)))
794 return true;
795
796 return false;
797}
798
Douglas Gregorb1373d02010-01-20 20:59:29 +0000799bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000800 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000801 if (D->getSuperClass() &&
802 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000803 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000804 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000805 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000806
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000807 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
808 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
809 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000810 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000811 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000812
Douglas Gregora59e3902010-01-21 23:27:09 +0000813 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000814}
815
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000816bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
817 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000818}
819
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000820bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000821 // 'ID' could be null when dealing with invalid code.
822 if (ObjCInterfaceDecl *ID = D->getClassInterface())
823 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
824 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000825
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000826 return VisitObjCImplDecl(D);
827}
828
829bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
830#if 0
831 // Issue callbacks for super class.
832 // FIXME: No source location information!
833 if (D->getSuperClass() &&
834 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000835 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000836 TU)))
837 return true;
838#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000839
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000840 return VisitObjCImplDecl(D);
841}
842
843bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
844 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
845 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
846 E = D->protocol_end();
847 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000848 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000849 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000850
851 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000852}
853
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000854bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
855 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
856 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
857 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000858
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000859 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000860}
861
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000862bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
863 return VisitDeclContext(D);
864}
865
Douglas Gregor01829d32010-08-31 14:41:23 +0000866bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
867 switch (Name.getName().getNameKind()) {
868 case clang::DeclarationName::Identifier:
869 case clang::DeclarationName::CXXLiteralOperatorName:
870 case clang::DeclarationName::CXXOperatorName:
871 case clang::DeclarationName::CXXUsingDirective:
872 return false;
873
874 case clang::DeclarationName::CXXConstructorName:
875 case clang::DeclarationName::CXXDestructorName:
876 case clang::DeclarationName::CXXConversionFunctionName:
877 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
878 return Visit(TSInfo->getTypeLoc());
879 return false;
880
881 case clang::DeclarationName::ObjCZeroArgSelector:
882 case clang::DeclarationName::ObjCOneArgSelector:
883 case clang::DeclarationName::ObjCMultiArgSelector:
884 // FIXME: Per-identifier location info?
885 return false;
886 }
887
888 return false;
889}
890
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000891bool CursorVisitor::VisitTemplateParameters(
892 const TemplateParameterList *Params) {
893 if (!Params)
894 return false;
895
896 for (TemplateParameterList::const_iterator P = Params->begin(),
897 PEnd = Params->end();
898 P != PEnd; ++P) {
899 if (Visit(MakeCXCursor(*P, TU)))
900 return true;
901 }
902
903 return false;
904}
905
Douglas Gregor0b36e612010-08-31 20:37:03 +0000906bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
907 switch (Name.getKind()) {
908 case TemplateName::Template:
909 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
910
911 case TemplateName::OverloadedTemplate:
912 // FIXME: We need a way to return multiple lookup results in a single
913 // cursor.
914 return false;
915
916 case TemplateName::DependentTemplate:
917 // FIXME: Visit nested-name-specifier.
918 return false;
919
920 case TemplateName::QualifiedTemplate:
921 // FIXME: Visit nested-name-specifier.
922 return Visit(MakeCursorTemplateRef(
923 Name.getAsQualifiedTemplateName()->getDecl(),
924 Loc, TU));
925 }
926
927 return false;
928}
929
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000930bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
931 switch (TAL.getArgument().getKind()) {
932 case TemplateArgument::Null:
933 case TemplateArgument::Integral:
934 return false;
935
936 case TemplateArgument::Pack:
937 // FIXME: Implement when variadic templates come along.
938 return false;
939
940 case TemplateArgument::Type:
941 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
942 return Visit(TSInfo->getTypeLoc());
943 return false;
944
945 case TemplateArgument::Declaration:
946 if (Expr *E = TAL.getSourceDeclExpression())
947 return Visit(MakeCXCursor(E, StmtParent, TU));
948 return false;
949
950 case TemplateArgument::Expression:
951 if (Expr *E = TAL.getSourceExpression())
952 return Visit(MakeCXCursor(E, StmtParent, TU));
953 return false;
954
955 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +0000956 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
957 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000958 }
959
960 return false;
961}
962
Ted Kremeneka0536d82010-05-07 01:04:29 +0000963bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
964 return VisitDeclContext(D);
965}
966
Douglas Gregor01829d32010-08-31 14:41:23 +0000967bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
968 return Visit(TL.getUnqualifiedLoc());
969}
970
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000971bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
972 ASTContext &Context = TU->getASTContext();
973
974 // Some builtin types (such as Objective-C's "id", "sel", and
975 // "Class") have associated declarations. Create cursors for those.
976 QualType VisitType;
977 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000978 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000979 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000980 case BuiltinType::Char_U:
981 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000982 case BuiltinType::Char16:
983 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000984 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000985 case BuiltinType::UInt:
986 case BuiltinType::ULong:
987 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000988 case BuiltinType::UInt128:
989 case BuiltinType::Char_S:
990 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000991 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000992 case BuiltinType::Short:
993 case BuiltinType::Int:
994 case BuiltinType::Long:
995 case BuiltinType::LongLong:
996 case BuiltinType::Int128:
997 case BuiltinType::Float:
998 case BuiltinType::Double:
999 case BuiltinType::LongDouble:
1000 case BuiltinType::NullPtr:
1001 case BuiltinType::Overload:
1002 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001003 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001004
1005 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001006 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001007
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001008 case BuiltinType::ObjCId:
1009 VisitType = Context.getObjCIdType();
1010 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001011
1012 case BuiltinType::ObjCClass:
1013 VisitType = Context.getObjCClassType();
1014 break;
1015
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001016 case BuiltinType::ObjCSel:
1017 VisitType = Context.getObjCSelType();
1018 break;
1019 }
1020
1021 if (!VisitType.isNull()) {
1022 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001023 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001024 TU));
1025 }
1026
1027 return false;
1028}
1029
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001030bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1031 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1032}
1033
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001034bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1035 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1036}
1037
1038bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1039 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1040}
1041
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001042bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1043 // FIXME: We can't visit the template template parameter, but there's
1044 // no context information with which we can match up the depth/index in the
1045 // type to the appropriate
1046 return false;
1047}
1048
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001049bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1050 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1051 return true;
1052
John McCallc12c5bb2010-05-15 11:32:37 +00001053 return false;
1054}
1055
1056bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1057 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1058 return true;
1059
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001060 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1061 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1062 TU)))
1063 return true;
1064 }
1065
1066 return false;
1067}
1068
1069bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001070 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001071}
1072
1073bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1074 return Visit(TL.getPointeeLoc());
1075}
1076
1077bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1078 return Visit(TL.getPointeeLoc());
1079}
1080
1081bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1082 return Visit(TL.getPointeeLoc());
1083}
1084
1085bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001086 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001087}
1088
1089bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001090 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001091}
1092
Douglas Gregor01829d32010-08-31 14:41:23 +00001093bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1094 bool SkipResultType) {
1095 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001096 return true;
1097
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001098 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001099 if (Decl *D = TL.getArg(I))
1100 if (Visit(MakeCXCursor(D, TU)))
1101 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001102
1103 return false;
1104}
1105
1106bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1107 if (Visit(TL.getElementLoc()))
1108 return true;
1109
1110 if (Expr *Size = TL.getSizeExpr())
1111 return Visit(MakeCXCursor(Size, StmtParent, TU));
1112
1113 return false;
1114}
1115
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001116bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1117 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001118 // Visit the template name.
1119 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1120 TL.getTemplateNameLoc()))
1121 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001122
1123 // Visit the template arguments.
1124 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1125 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1126 return true;
1127
1128 return false;
1129}
1130
Douglas Gregor2332c112010-01-21 20:48:56 +00001131bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1132 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1133}
1134
1135bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1136 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1137 return Visit(TSInfo->getTypeLoc());
1138
1139 return false;
1140}
1141
Douglas Gregora59e3902010-01-21 23:27:09 +00001142bool CursorVisitor::VisitStmt(Stmt *S) {
1143 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1144 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001145 if (Stmt *C = *Child)
1146 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1147 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001148 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001149
Douglas Gregora59e3902010-01-21 23:27:09 +00001150 return false;
1151}
1152
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001153bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1154 // Specially handle CaseStmts because they can be nested, e.g.:
1155 //
1156 // case 1:
1157 // case 2:
1158 //
1159 // In this case the second CaseStmt is the child of the first. Walking
1160 // these recursively can blow out the stack.
1161 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1162 while (true) {
1163 // Set the Parent field to Cursor, then back to its old value once we're
1164 // done.
1165 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1166
1167 if (Stmt *LHS = S->getLHS())
1168 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1169 return true;
1170 if (Stmt *RHS = S->getRHS())
1171 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1172 return true;
1173 if (Stmt *SubStmt = S->getSubStmt()) {
1174 if (!isa<CaseStmt>(SubStmt))
1175 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1176
1177 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1178 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1179 Cursor = MakeCXCursor(CS, StmtParent, TU);
1180 if (RegionOfInterest.isValid()) {
1181 SourceRange Range = CS->getSourceRange();
1182 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1183 return false;
1184 }
1185
1186 switch (Visitor(Cursor, Parent, ClientData)) {
1187 case CXChildVisit_Break: return true;
1188 case CXChildVisit_Continue: return false;
1189 case CXChildVisit_Recurse:
1190 // Perform tail-recursion manually.
1191 S = CS;
1192 continue;
1193 }
1194 }
1195 return false;
1196 }
1197}
1198
Douglas Gregora59e3902010-01-21 23:27:09 +00001199bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1200 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1201 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +00001202 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001203 return true;
1204 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001205
Douglas Gregora59e3902010-01-21 23:27:09 +00001206 return false;
1207}
1208
Douglas Gregorf5bab412010-01-22 01:00:11 +00001209bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1210 if (VarDecl *Var = S->getConditionVariable()) {
1211 if (Visit(MakeCXCursor(Var, TU)))
1212 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001213 }
1214
Douglas Gregor263b47b2010-01-25 16:12:32 +00001215 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1216 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001217 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1218 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001219 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1220 return true;
1221
1222 return false;
1223}
1224
1225bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1226 if (VarDecl *Var = S->getConditionVariable()) {
1227 if (Visit(MakeCXCursor(Var, TU)))
1228 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001229 }
1230
Douglas Gregor263b47b2010-01-25 16:12:32 +00001231 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1232 return true;
1233 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1234 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001235
Douglas Gregor263b47b2010-01-25 16:12:32 +00001236 return false;
1237}
1238
1239bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1240 if (VarDecl *Var = S->getConditionVariable()) {
1241 if (Visit(MakeCXCursor(Var, TU)))
1242 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001243 }
1244
Douglas Gregor263b47b2010-01-25 16:12:32 +00001245 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1246 return true;
1247 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001248 return true;
1249
Douglas Gregor263b47b2010-01-25 16:12:32 +00001250 return false;
1251}
1252
1253bool CursorVisitor::VisitForStmt(ForStmt *S) {
1254 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1255 return true;
1256 if (VarDecl *Var = S->getConditionVariable()) {
1257 if (Visit(MakeCXCursor(Var, TU)))
1258 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001259 }
1260
Douglas Gregor263b47b2010-01-25 16:12:32 +00001261 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1262 return true;
1263 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1264 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001265 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1266 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001267
Douglas Gregorf5bab412010-01-22 01:00:11 +00001268 return false;
1269}
1270
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001271bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1272 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1273 return true;
1274
1275 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1276 return true;
1277
1278 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1279 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1280 return true;
1281
1282 return false;
1283}
1284
Ted Kremenek3064ef92010-08-27 21:34:58 +00001285bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1286 if (D->isDefinition()) {
1287 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1288 E = D->bases_end(); I != E; ++I) {
1289 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1290 return true;
1291 }
1292 }
1293
1294 return VisitTagDecl(D);
1295}
1296
1297
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001298bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1299 return Visit(B->getBlockDecl());
1300}
1301
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001302bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1303 // FIXME: Visit fields as well?
1304 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1305 return true;
1306
1307 return VisitExpr(E);
1308}
1309
Douglas Gregor336fd812010-01-23 00:40:08 +00001310bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1311 if (E->isArgumentType()) {
1312 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1313 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001314
Douglas Gregor336fd812010-01-23 00:40:08 +00001315 return false;
1316 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001317
Douglas Gregor336fd812010-01-23 00:40:08 +00001318 return VisitExpr(E);
1319}
1320
1321bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1322 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1323 if (Visit(TSInfo->getTypeLoc()))
1324 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001325
Douglas Gregor336fd812010-01-23 00:40:08 +00001326 return VisitCastExpr(E);
1327}
1328
1329bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1330 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1331 if (Visit(TSInfo->getTypeLoc()))
1332 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001333
Douglas Gregor336fd812010-01-23 00:40:08 +00001334 return VisitExpr(E);
1335}
1336
Douglas Gregor648220e2010-08-10 15:02:34 +00001337bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1338 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1339 Visit(E->getArgTInfo2()->getTypeLoc());
1340}
1341
1342bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1343 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1344 return true;
1345
1346 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1347}
1348
Douglas Gregorc2350e52010-03-08 16:40:19 +00001349bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001350 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1351 if (Visit(TSInfo->getTypeLoc()))
1352 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001353
1354 return VisitExpr(E);
1355}
1356
Douglas Gregor81d34662010-04-20 15:39:42 +00001357bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1358 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1359}
1360
1361
Ted Kremenek09dfa372010-02-18 05:46:33 +00001362bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001363 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1364 i != e; ++i)
1365 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001366 return true;
1367
1368 return false;
1369}
1370
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001371extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001372CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1373 int displayDiagnostics) {
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00001374 // We use crash recovery to make some of our APIs more reliable, implicitly
1375 // enable it.
1376 llvm::CrashRecoveryContext::Enable();
1377
Douglas Gregora030b7c2010-01-22 20:35:53 +00001378 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001379 if (excludeDeclarationsFromPCH)
1380 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001381 if (displayDiagnostics)
1382 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001383 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00001384}
1385
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001386void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001387 if (CIdx)
1388 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +00001389 if (getenv("LIBCLANG_TIMING"))
1390 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001391}
1392
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001393void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001394 if (CIdx) {
1395 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1396 CXXIdx->setUseExternalASTGeneration(value);
1397 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001398}
1399
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001400CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001401 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001402 if (!CIdx)
1403 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001404
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001405 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001406
Douglas Gregor28019772010-04-05 23:52:57 +00001407 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001408 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001409 CXXIdx->getOnlyLocalDecls(),
1410 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001411}
1412
Douglas Gregorb1c031b2010-08-09 22:28:58 +00001413unsigned clang_defaultEditingTranslationUnitOptions() {
1414 return CXTranslationUnit_PrecompiledPreamble;
1415}
1416
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001417CXTranslationUnit
1418clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1419 const char *source_filename,
1420 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001421 const char **command_line_args,
1422 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001423 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00001424 return clang_parseTranslationUnit(CIdx, source_filename,
1425 command_line_args, num_command_line_args,
1426 unsaved_files, num_unsaved_files,
1427 CXTranslationUnit_DetailedPreprocessingRecord);
1428}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001429
1430struct ParseTranslationUnitInfo {
1431 CXIndex CIdx;
1432 const char *source_filename;
1433 const char **command_line_args;
1434 int num_command_line_args;
1435 struct CXUnsavedFile *unsaved_files;
1436 unsigned num_unsaved_files;
1437 unsigned options;
1438 CXTranslationUnit result;
1439};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001440static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001441 ParseTranslationUnitInfo *PTUI =
1442 static_cast<ParseTranslationUnitInfo*>(UserData);
1443 CXIndex CIdx = PTUI->CIdx;
1444 const char *source_filename = PTUI->source_filename;
1445 const char **command_line_args = PTUI->command_line_args;
1446 int num_command_line_args = PTUI->num_command_line_args;
1447 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1448 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1449 unsigned options = PTUI->options;
1450 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00001451
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001452 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001453 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001454
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001455 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1456
Douglas Gregor44c181a2010-07-23 00:33:23 +00001457 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00001458 bool CompleteTranslationUnit
1459 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001460 bool CacheCodeCompetionResults
1461 = options & CXTranslationUnit_CacheCompletionResults;
1462
Douglas Gregor5352ac02010-01-28 00:27:43 +00001463 // Configure the diagnostics.
1464 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001465 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1466 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001467
Douglas Gregor4db64a42010-01-23 00:14:00 +00001468 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1469 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001470 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001471 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001472 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001473 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1474 Buffer));
1475 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001476
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001477 if (!CXXIdx->getUseExternalASTGeneration()) {
1478 llvm::SmallVector<const char *, 16> Args;
1479
1480 // The 'source_filename' argument is optional. If the caller does not
1481 // specify it then it is assumed that the source file is specified
1482 // in the actual argument list.
1483 if (source_filename)
1484 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001485
1486 // Since the Clang C library is primarily used by batch tools dealing with
1487 // (often very broken) source code, where spell-checking can have a
1488 // significant negative impact on performance (particularly when
1489 // precompiled headers are involved), we disable it by default.
1490 // Note that we place this argument early in the list, so that it can be
1491 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001492 Args.push_back("-fno-spell-checking");
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001493
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001494 Args.insert(Args.end(), command_line_args,
1495 command_line_args + num_command_line_args);
Douglas Gregor5a430212010-07-21 18:52:53 +00001496
Douglas Gregor44c181a2010-07-23 00:33:23 +00001497 // Do we need the detailed preprocessing record?
Douglas Gregor5a430212010-07-21 18:52:53 +00001498 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1499 Args.push_back("-Xclang");
1500 Args.push_back("-detailed-preprocessing-record");
1501 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001502
Douglas Gregor5352ac02010-01-28 00:27:43 +00001503 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001504
Ted Kremenek29b72842010-01-07 22:49:05 +00001505#ifdef USE_CRASHTRACER
1506 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001507#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001508
Daniel Dunbar94220972009-12-05 02:17:18 +00001509 llvm::OwningPtr<ASTUnit> Unit(
1510 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001511 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001512 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001513 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001514 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001515 RemappedFiles.size(),
Douglas Gregor44c181a2010-07-23 00:33:23 +00001516 /*CaptureDiagnostics=*/true,
Douglas Gregordf95a132010-08-09 20:45:32 +00001517 PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001518 CompleteTranslationUnit,
1519 CacheCodeCompetionResults));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001520
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001521 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001522 // Make sure to check that 'Unit' is non-NULL.
1523 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001524 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1525 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001526 D != DEnd; ++D) {
1527 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001528 CXString Msg = clang_formatDiagnostic(&Diag,
1529 clang_defaultDiagnosticDisplayOptions());
1530 fprintf(stderr, "%s\n", clang_getCString(Msg));
1531 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001532 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001533#ifdef LLVM_ON_WIN32
1534 // On Windows, force a flush, since there may be multiple copies of
1535 // stderr and stdout in the file system, all with different buffers
1536 // but writing to the same device.
1537 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001538#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001539 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001540 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001541
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001542 PTUI->result = Unit.take();
1543 return;
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001544 }
1545
Ted Kremenek139ba862009-10-22 00:03:57 +00001546 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001547 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001548
Ted Kremenek139ba862009-10-22 00:03:57 +00001549 // First add the complete path to the 'clang' executable.
1550 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001551 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001552
Ted Kremenek139ba862009-10-22 00:03:57 +00001553 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001554 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001555
Ted Kremenek139ba862009-10-22 00:03:57 +00001556 // The 'source_filename' argument is optional. If the caller does not
1557 // specify it then it is assumed that the source file is specified
1558 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001559 if (source_filename)
1560 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001561
Steve Naroff37b5ac22009-10-15 20:50:09 +00001562 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001563 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001564 char astTmpFile[L_tmpnam];
1565 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00001566
1567 // Since the Clang C library is primarily used by batch tools dealing with
1568 // (often very broken) source code, where spell-checking can have a
1569 // significant negative impact on performance (particularly when
1570 // precompiled headers are involved), we disable it by default.
1571 // Note that we place this argument early in the list, so that it can be
1572 // overridden by the caller with "-fspell-checking".
Douglas Gregora0068fc2010-07-09 17:35:33 +00001573 argv.push_back("-fno-spell-checking");
Ted Kremenek139ba862009-10-22 00:03:57 +00001574
Douglas Gregor4db64a42010-01-23 00:14:00 +00001575 // Remap any unsaved files to temporary files.
1576 std::vector<llvm::sys::Path> TemporaryFiles;
1577 std::vector<std::string> RemapArgs;
1578 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001579 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001580
Douglas Gregor4db64a42010-01-23 00:14:00 +00001581 // The pointers into the elements of RemapArgs are stable because we
1582 // won't be adding anything to RemapArgs after this point.
1583 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1584 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001585
Ted Kremenek139ba862009-10-22 00:03:57 +00001586 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1587 for (int i = 0; i < num_command_line_args; ++i)
1588 if (const char *arg = command_line_args[i]) {
1589 if (strcmp(arg, "-o") == 0) {
1590 ++i; // Also skip the matching argument.
1591 continue;
1592 }
1593 if (strcmp(arg, "-emit-ast") == 0 ||
1594 strcmp(arg, "-c") == 0 ||
1595 strcmp(arg, "-fsyntax-only") == 0) {
1596 continue;
1597 }
1598
1599 // Keep the argument.
1600 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001601 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001602
Douglas Gregord93256e2010-01-28 06:00:51 +00001603 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001604 char tmpFileResults[L_tmpnam];
1605 char *tmpResultsFileName = tmpnam(tmpFileResults);
1606 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001607 TemporaryFiles.push_back(DiagnosticsFile);
1608 argv.push_back("-fdiagnostics-binary");
1609
Douglas Gregor44c181a2010-07-23 00:33:23 +00001610 // Do we need the detailed preprocessing record?
1611 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1612 argv.push_back("-Xclang");
1613 argv.push_back("-detailed-preprocessing-record");
1614 }
1615
Ted Kremenek139ba862009-10-22 00:03:57 +00001616 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001617 argv.push_back(NULL);
1618
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001619 // Invoke 'clang'.
1620 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1621 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001622 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001623 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1624 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001625 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001626 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001627 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001628
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001629 if (!ErrMsg.empty()) {
1630 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001631 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001632 I != E; ++I) {
1633 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001634 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001635 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001636 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001637
Daniel Dunbar32141c82010-02-23 20:23:45 +00001638 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001639 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001640
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001641 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001642 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001643 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001644 RemappedFiles.size(),
1645 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001646 if (ATU) {
1647 LoadSerializedDiagnostics(DiagnosticsFile,
1648 num_unsaved_files, unsaved_files,
1649 ATU->getFileManager(),
1650 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001651 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001652 } else if (CXXIdx->getDisplayDiagnostics()) {
1653 // We failed to load the ASTUnit, but we can still deserialize the
1654 // diagnostics and emit them.
1655 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001656 Diagnostic Diag;
1657 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001658 // FIXME: Faked LangOpts!
1659 LangOptions LangOpts;
1660 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1661 LoadSerializedDiagnostics(DiagnosticsFile,
1662 num_unsaved_files, unsaved_files,
1663 FileMgr, SourceMgr, Diags);
1664 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1665 DEnd = Diags.end();
1666 D != DEnd; ++D) {
1667 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001668 CXString Msg = clang_formatDiagnostic(&Diag,
1669 clang_defaultDiagnosticDisplayOptions());
1670 fprintf(stderr, "%s\n", clang_getCString(Msg));
1671 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001672 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001673
1674#ifdef LLVM_ON_WIN32
1675 // On Windows, force a flush, since there may be multiple copies of
1676 // stderr and stdout in the file system, all with different buffers
1677 // but writing to the same device.
1678 fflush(stderr);
1679#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001680 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001681
Douglas Gregor313e26c2010-02-18 23:35:40 +00001682 if (ATU) {
1683 // Make the translation unit responsible for destroying all temporary files.
1684 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1685 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001686 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor313e26c2010-02-18 23:35:40 +00001687 } else {
1688 // Destroy all of the temporary files now; they can't be referenced any
1689 // longer.
1690 llvm::sys::Path(astTmpFile).eraseFromDisk();
1691 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1692 TemporaryFiles[i].eraseFromDisk();
1693 }
1694
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001695 PTUI->result = ATU;
1696}
1697CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1698 const char *source_filename,
1699 const char **command_line_args,
1700 int num_command_line_args,
1701 struct CXUnsavedFile *unsaved_files,
1702 unsigned num_unsaved_files,
1703 unsigned options) {
1704 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
1705 num_command_line_args, unsaved_files, num_unsaved_files,
1706 options, 0 };
1707 llvm::CrashRecoveryContext CRC;
1708
1709 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00001710 fprintf(stderr, "libclang: crash detected during parsing: {\n");
1711 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
1712 fprintf(stderr, " 'command_line_args' : [");
1713 for (int i = 0; i != num_command_line_args; ++i) {
1714 if (i)
1715 fprintf(stderr, ", ");
1716 fprintf(stderr, "'%s'", command_line_args[i]);
1717 }
1718 fprintf(stderr, "],\n");
1719 fprintf(stderr, " 'unsaved_files' : [");
1720 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1721 if (i)
1722 fprintf(stderr, ", ");
1723 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1724 unsaved_files[i].Length);
1725 }
1726 fprintf(stderr, "],\n");
1727 fprintf(stderr, " 'options' : %d,\n", options);
1728 fprintf(stderr, "}\n");
1729
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001730 return 0;
1731 }
1732
1733 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001734}
1735
Douglas Gregor19998442010-08-13 15:35:05 +00001736unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
1737 return CXSaveTranslationUnit_None;
1738}
1739
1740int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
1741 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001742 if (!TU)
1743 return 1;
1744
1745 return static_cast<ASTUnit *>(TU)->Save(FileName);
1746}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00001747
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001748void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001749 if (CTUnit) {
1750 // If the translation unit has been marked as unsafe to free, just discard
1751 // it.
1752 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
1753 return;
1754
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001755 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001756 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001757}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001758
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001759unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
1760 return CXReparse_None;
1761}
1762
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001763struct ReparseTranslationUnitInfo {
1764 CXTranslationUnit TU;
1765 unsigned num_unsaved_files;
1766 struct CXUnsavedFile *unsaved_files;
1767 unsigned options;
1768 int result;
1769};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001770static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001771 ReparseTranslationUnitInfo *RTUI =
1772 static_cast<ReparseTranslationUnitInfo*>(UserData);
1773 CXTranslationUnit TU = RTUI->TU;
1774 unsigned num_unsaved_files = RTUI->num_unsaved_files;
1775 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
1776 unsigned options = RTUI->options;
1777 (void) options;
1778 RTUI->result = 1;
1779
Douglas Gregorabc563f2010-07-19 21:46:24 +00001780 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001781 return;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001782
1783 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1784 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1785 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1786 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001787 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001788 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1789 Buffer));
1790 }
1791
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001792 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1793 RemappedFiles.size()))
1794 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001795}
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001796int clang_reparseTranslationUnit(CXTranslationUnit TU,
1797 unsigned num_unsaved_files,
1798 struct CXUnsavedFile *unsaved_files,
1799 unsigned options) {
1800 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
1801 options, 0 };
1802 llvm::CrashRecoveryContext CRC;
1803
1804 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00001805 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00001806 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
1807 return 1;
1808 }
1809
1810 return RTUI.result;
1811}
1812
Douglas Gregordf95a132010-08-09 20:45:32 +00001813
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001814CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001815 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001816 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001817
Steve Naroff77accc12009-09-03 18:19:54 +00001818 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001819 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001820}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001821
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001822CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001823 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001824 return Result;
1825}
1826
Ted Kremenekfb480492010-01-13 21:46:36 +00001827} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001828
Ted Kremenekfb480492010-01-13 21:46:36 +00001829//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001830// CXSourceLocation and CXSourceRange Operations.
1831//===----------------------------------------------------------------------===//
1832
Douglas Gregorb9790342010-01-22 21:44:22 +00001833extern "C" {
1834CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001835 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001836 return Result;
1837}
1838
1839unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001840 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1841 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1842 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001843}
1844
1845CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1846 CXFile file,
1847 unsigned line,
1848 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00001849 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00001850 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00001851
Douglas Gregorb9790342010-01-22 21:44:22 +00001852 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1853 SourceLocation SLoc
1854 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001855 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001856 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001857
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00001858 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001859}
1860
Douglas Gregor5352ac02010-01-28 00:27:43 +00001861CXSourceRange clang_getNullRange() {
1862 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1863 return Result;
1864}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001865
Douglas Gregor5352ac02010-01-28 00:27:43 +00001866CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1867 if (begin.ptr_data[0] != end.ptr_data[0] ||
1868 begin.ptr_data[1] != end.ptr_data[1])
1869 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001870
1871 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001872 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001873 return Result;
1874}
1875
Douglas Gregor46766dc2010-01-26 19:19:08 +00001876void clang_getInstantiationLocation(CXSourceLocation location,
1877 CXFile *file,
1878 unsigned *line,
1879 unsigned *column,
1880 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001881 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1882
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001883 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001884 if (file)
1885 *file = 0;
1886 if (line)
1887 *line = 0;
1888 if (column)
1889 *column = 0;
1890 if (offset)
1891 *offset = 0;
1892 return;
1893 }
1894
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001895 const SourceManager &SM =
1896 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001897 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001898
1899 if (file)
1900 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1901 if (line)
1902 *line = SM.getInstantiationLineNumber(InstLoc);
1903 if (column)
1904 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001905 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001906 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001907}
1908
Douglas Gregor1db19de2010-01-19 21:36:55 +00001909CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001910 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001911 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001912 return Result;
1913}
1914
1915CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001916 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001917 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001918 return Result;
1919}
1920
Douglas Gregorb9790342010-01-22 21:44:22 +00001921} // end: extern "C"
1922
Douglas Gregor1db19de2010-01-19 21:36:55 +00001923//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001924// CXFile Operations.
1925//===----------------------------------------------------------------------===//
1926
1927extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001928CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001929 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001930 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001931
Steve Naroff88145032009-10-27 14:35:18 +00001932 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001933 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001934}
1935
1936time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001937 if (!SFile)
1938 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001939
Steve Naroff88145032009-10-27 14:35:18 +00001940 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1941 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001942}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001943
Douglas Gregorb9790342010-01-22 21:44:22 +00001944CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1945 if (!tu)
1946 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001947
Douglas Gregorb9790342010-01-22 21:44:22 +00001948 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001949
Douglas Gregorb9790342010-01-22 21:44:22 +00001950 FileManager &FMgr = CXXUnit->getFileManager();
1951 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1952 return const_cast<FileEntry *>(File);
1953}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001954
Ted Kremenekfb480492010-01-13 21:46:36 +00001955} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001956
Ted Kremenekfb480492010-01-13 21:46:36 +00001957//===----------------------------------------------------------------------===//
1958// CXCursor Operations.
1959//===----------------------------------------------------------------------===//
1960
Ted Kremenekfb480492010-01-13 21:46:36 +00001961static Decl *getDeclFromExpr(Stmt *E) {
1962 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1963 return RefExpr->getDecl();
1964 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1965 return ME->getMemberDecl();
1966 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1967 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001968
Ted Kremenekfb480492010-01-13 21:46:36 +00001969 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1970 return getDeclFromExpr(CE->getCallee());
1971 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1972 return getDeclFromExpr(CE->getSubExpr());
1973 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1974 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001975
Ted Kremenekfb480492010-01-13 21:46:36 +00001976 return 0;
1977}
1978
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001979static SourceLocation getLocationFromExpr(Expr *E) {
1980 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1981 return /*FIXME:*/Msg->getLeftLoc();
1982 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1983 return DRE->getLocation();
1984 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1985 return Member->getMemberLoc();
1986 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1987 return Ivar->getLocation();
1988 return E->getLocStart();
1989}
1990
Ted Kremenekfb480492010-01-13 21:46:36 +00001991extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001992
1993unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001994 CXCursorVisitor visitor,
1995 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001996 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001997
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001998 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1999 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002000 return CursorVis.VisitChildren(parent);
2001}
2002
Douglas Gregor78205d42010-01-20 21:45:58 +00002003static CXString getDeclSpelling(Decl *D) {
2004 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2005 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002006 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002007
Douglas Gregor78205d42010-01-20 21:45:58 +00002008 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002009 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002010
Douglas Gregor78205d42010-01-20 21:45:58 +00002011 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2012 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2013 // and returns different names. NamedDecl returns the class name and
2014 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002015 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002016
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002017 llvm::SmallString<1024> S;
2018 llvm::raw_svector_ostream os(S);
2019 ND->printName(os);
2020
2021 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002022}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002023
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002024CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002025 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002026 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002027
Steve Narofff334b4e2009-09-02 18:26:48 +00002028 if (clang_isReference(C.kind)) {
2029 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002030 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002031 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002032 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002033 }
2034 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002035 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002036 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002037 }
2038 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002039 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002040 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002041 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002042 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002043 case CXCursor_CXXBaseSpecifier: {
2044 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2045 return createCXString(B->getType().getAsString());
2046 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002047 case CXCursor_TypeRef: {
2048 TypeDecl *Type = getCursorTypeRef(C).first;
2049 assert(Type && "Missing type decl");
2050
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002051 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2052 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002053 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002054 case CXCursor_TemplateRef: {
2055 TemplateDecl *Template = getCursorTemplateRef(C).first;
2056 assert(Template && "Missing type decl");
2057
2058 return createCXString(Template->getNameAsString());
2059 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002060
Daniel Dunbaracca7252009-11-30 20:42:49 +00002061 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002062 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002063 }
2064 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002065
2066 if (clang_isExpression(C.kind)) {
2067 Decl *D = getDeclFromExpr(getCursorExpr(C));
2068 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002069 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002070 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002071 }
2072
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002073 if (C.kind == CXCursor_MacroInstantiation)
2074 return createCXString(getCursorMacroInstantiation(C)->getName()
2075 ->getNameStart());
2076
Douglas Gregor572feb22010-03-18 18:04:21 +00002077 if (C.kind == CXCursor_MacroDefinition)
2078 return createCXString(getCursorMacroDefinition(C)->getName()
2079 ->getNameStart());
2080
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002081 if (clang_isDeclaration(C.kind))
2082 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002083
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002084 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002085}
2086
Ted Kremeneke68fff62010-02-17 00:41:32 +00002087CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002088 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002089 case CXCursor_FunctionDecl:
2090 return createCXString("FunctionDecl");
2091 case CXCursor_TypedefDecl:
2092 return createCXString("TypedefDecl");
2093 case CXCursor_EnumDecl:
2094 return createCXString("EnumDecl");
2095 case CXCursor_EnumConstantDecl:
2096 return createCXString("EnumConstantDecl");
2097 case CXCursor_StructDecl:
2098 return createCXString("StructDecl");
2099 case CXCursor_UnionDecl:
2100 return createCXString("UnionDecl");
2101 case CXCursor_ClassDecl:
2102 return createCXString("ClassDecl");
2103 case CXCursor_FieldDecl:
2104 return createCXString("FieldDecl");
2105 case CXCursor_VarDecl:
2106 return createCXString("VarDecl");
2107 case CXCursor_ParmDecl:
2108 return createCXString("ParmDecl");
2109 case CXCursor_ObjCInterfaceDecl:
2110 return createCXString("ObjCInterfaceDecl");
2111 case CXCursor_ObjCCategoryDecl:
2112 return createCXString("ObjCCategoryDecl");
2113 case CXCursor_ObjCProtocolDecl:
2114 return createCXString("ObjCProtocolDecl");
2115 case CXCursor_ObjCPropertyDecl:
2116 return createCXString("ObjCPropertyDecl");
2117 case CXCursor_ObjCIvarDecl:
2118 return createCXString("ObjCIvarDecl");
2119 case CXCursor_ObjCInstanceMethodDecl:
2120 return createCXString("ObjCInstanceMethodDecl");
2121 case CXCursor_ObjCClassMethodDecl:
2122 return createCXString("ObjCClassMethodDecl");
2123 case CXCursor_ObjCImplementationDecl:
2124 return createCXString("ObjCImplementationDecl");
2125 case CXCursor_ObjCCategoryImplDecl:
2126 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002127 case CXCursor_CXXMethod:
2128 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002129 case CXCursor_UnexposedDecl:
2130 return createCXString("UnexposedDecl");
2131 case CXCursor_ObjCSuperClassRef:
2132 return createCXString("ObjCSuperClassRef");
2133 case CXCursor_ObjCProtocolRef:
2134 return createCXString("ObjCProtocolRef");
2135 case CXCursor_ObjCClassRef:
2136 return createCXString("ObjCClassRef");
2137 case CXCursor_TypeRef:
2138 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002139 case CXCursor_TemplateRef:
2140 return createCXString("TemplateRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002141 case CXCursor_UnexposedExpr:
2142 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002143 case CXCursor_BlockExpr:
2144 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002145 case CXCursor_DeclRefExpr:
2146 return createCXString("DeclRefExpr");
2147 case CXCursor_MemberRefExpr:
2148 return createCXString("MemberRefExpr");
2149 case CXCursor_CallExpr:
2150 return createCXString("CallExpr");
2151 case CXCursor_ObjCMessageExpr:
2152 return createCXString("ObjCMessageExpr");
2153 case CXCursor_UnexposedStmt:
2154 return createCXString("UnexposedStmt");
2155 case CXCursor_InvalidFile:
2156 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002157 case CXCursor_InvalidCode:
2158 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002159 case CXCursor_NoDeclFound:
2160 return createCXString("NoDeclFound");
2161 case CXCursor_NotImplemented:
2162 return createCXString("NotImplemented");
2163 case CXCursor_TranslationUnit:
2164 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002165 case CXCursor_UnexposedAttr:
2166 return createCXString("UnexposedAttr");
2167 case CXCursor_IBActionAttr:
2168 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002169 case CXCursor_IBOutletAttr:
2170 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002171 case CXCursor_IBOutletCollectionAttr:
2172 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002173 case CXCursor_PreprocessingDirective:
2174 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002175 case CXCursor_MacroDefinition:
2176 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002177 case CXCursor_MacroInstantiation:
2178 return createCXString("macro instantiation");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002179 case CXCursor_Namespace:
2180 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002181 case CXCursor_LinkageSpec:
2182 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002183 case CXCursor_CXXBaseSpecifier:
2184 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002185 case CXCursor_Constructor:
2186 return createCXString("CXXConstructor");
2187 case CXCursor_Destructor:
2188 return createCXString("CXXDestructor");
2189 case CXCursor_ConversionFunction:
2190 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002191 case CXCursor_TemplateTypeParameter:
2192 return createCXString("TemplateTypeParameter");
2193 case CXCursor_NonTypeTemplateParameter:
2194 return createCXString("NonTypeTemplateParameter");
2195 case CXCursor_TemplateTemplateParameter:
2196 return createCXString("TemplateTemplateParameter");
2197 case CXCursor_FunctionTemplate:
2198 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002199 case CXCursor_ClassTemplate:
2200 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002201 case CXCursor_ClassTemplatePartialSpecialization:
2202 return createCXString("ClassTemplatePartialSpecialization");
Steve Naroff89922f82009-08-31 00:59:03 +00002203 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002204
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002205 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002206 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002207}
Steve Naroff89922f82009-08-31 00:59:03 +00002208
Ted Kremeneke68fff62010-02-17 00:41:32 +00002209enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2210 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002211 CXClientData client_data) {
2212 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2213 *BestCursor = cursor;
2214 return CXChildVisit_Recurse;
2215}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002216
Douglas Gregorb9790342010-01-22 21:44:22 +00002217CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2218 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002219 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002220
Douglas Gregorb9790342010-01-22 21:44:22 +00002221 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002222 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2223
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002224 // Translate the given source location to make it point at the beginning of
2225 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002226 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002227
2228 // Guard against an invalid SourceLocation, or we may assert in one
2229 // of the following calls.
2230 if (SLoc.isInvalid())
2231 return clang_getNullCursor();
2232
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002233 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2234 CXXUnit->getASTContext().getLangOptions());
2235
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002236 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2237 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002238 // FIXME: Would be great to have a "hint" cursor, then walk from that
2239 // hint cursor upward until we find a cursor whose source range encloses
2240 // the region of interest, rather than starting from the translation unit.
2241 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00002242 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002243 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002244 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00002245 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002246 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00002247}
2248
Ted Kremenek73885552009-11-17 19:28:59 +00002249CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00002250 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00002251}
2252
2253unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002254 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00002255}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002256
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002257unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00002258 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2259}
2260
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002261unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00002262 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2263}
Steve Naroff2d4d6292009-08-31 14:26:51 +00002264
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002265unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00002266 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2267}
2268
Douglas Gregor97b98722010-01-19 23:20:36 +00002269unsigned clang_isExpression(enum CXCursorKind K) {
2270 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2271}
2272
2273unsigned clang_isStatement(enum CXCursorKind K) {
2274 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2275}
2276
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002277unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2278 return K == CXCursor_TranslationUnit;
2279}
2280
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002281unsigned clang_isPreprocessing(enum CXCursorKind K) {
2282 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2283}
2284
Ted Kremenekad6eff62010-03-08 21:17:29 +00002285unsigned clang_isUnexposed(enum CXCursorKind K) {
2286 switch (K) {
2287 case CXCursor_UnexposedDecl:
2288 case CXCursor_UnexposedExpr:
2289 case CXCursor_UnexposedStmt:
2290 case CXCursor_UnexposedAttr:
2291 return true;
2292 default:
2293 return false;
2294 }
2295}
2296
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002297CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00002298 return C.kind;
2299}
2300
Douglas Gregor98258af2010-01-18 22:46:11 +00002301CXSourceLocation clang_getCursorLocation(CXCursor C) {
2302 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002303 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002304 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002305 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2306 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002307 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002308 }
2309
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002310 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002311 std::pair<ObjCProtocolDecl *, SourceLocation> P
2312 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002313 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002314 }
2315
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002316 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00002317 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2318 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002319 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002320 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002321
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002322 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002323 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00002324 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002325 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002326
2327 case CXCursor_TemplateRef: {
2328 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2329 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2330 }
2331
Ted Kremenek3064ef92010-08-27 21:34:58 +00002332 case CXCursor_CXXBaseSpecifier: {
2333 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2334 return clang_getNullLocation();
2335 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002336
Douglas Gregorf46034a2010-01-18 23:41:10 +00002337 default:
2338 // FIXME: Need a way to enumerate all non-reference cases.
2339 llvm_unreachable("Missed a reference kind");
2340 }
Douglas Gregor98258af2010-01-18 22:46:11 +00002341 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002342
2343 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002344 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00002345 getLocationFromExpr(getCursorExpr(C)));
2346
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002347 if (C.kind == CXCursor_PreprocessingDirective) {
2348 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2349 return cxloc::translateSourceLocation(getCursorContext(C), L);
2350 }
Douglas Gregor48072312010-03-18 15:23:44 +00002351
2352 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002353 SourceLocation L
2354 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00002355 return cxloc::translateSourceLocation(getCursorContext(C), L);
2356 }
Douglas Gregor572feb22010-03-18 18:04:21 +00002357
2358 if (C.kind == CXCursor_MacroDefinition) {
2359 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2360 return cxloc::translateSourceLocation(getCursorContext(C), L);
2361 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002362
Ted Kremenek9a700d22010-05-12 06:16:13 +00002363 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00002364 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00002365
Douglas Gregorf46034a2010-01-18 23:41:10 +00002366 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00002367 SourceLocation Loc = D->getLocation();
2368 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2369 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00002370 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00002371}
Douglas Gregora7bde202010-01-19 00:34:46 +00002372
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002373} // end extern "C"
2374
2375static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00002376 if (clang_isReference(C.kind)) {
2377 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002378 case CXCursor_ObjCSuperClassRef:
2379 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002380
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002381 case CXCursor_ObjCProtocolRef:
2382 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002383
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002384 case CXCursor_ObjCClassRef:
2385 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002386
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002387 case CXCursor_TypeRef:
2388 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00002389
2390 case CXCursor_TemplateRef:
2391 return getCursorTemplateRef(C).second;
2392
Ted Kremenek3064ef92010-08-27 21:34:58 +00002393 case CXCursor_CXXBaseSpecifier:
2394 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2395 return SourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002396
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002397 default:
2398 // FIXME: Need a way to enumerate all non-reference cases.
2399 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00002400 }
2401 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002402
2403 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002404 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002405
2406 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002407 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002408
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002409 if (C.kind == CXCursor_PreprocessingDirective)
2410 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00002411
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002412 if (C.kind == CXCursor_MacroInstantiation)
2413 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00002414
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002415 if (C.kind == CXCursor_MacroDefinition)
2416 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002417
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002418 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2419 return getCursorDecl(C)->getSourceRange();
2420
2421 return SourceRange();
2422}
2423
2424extern "C" {
2425
2426CXSourceRange clang_getCursorExtent(CXCursor C) {
2427 SourceRange R = getRawCursorExtent(C);
2428 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00002429 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002430
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002431 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00002432}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002433
2434CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002435 if (clang_isInvalid(C.kind))
2436 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002437
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002438 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00002439 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002440 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002441
Douglas Gregor97b98722010-01-19 23:20:36 +00002442 if (clang_isExpression(C.kind)) {
2443 Decl *D = getDeclFromExpr(getCursorExpr(C));
2444 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002445 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00002446 return clang_getNullCursor();
2447 }
2448
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002449 if (C.kind == CXCursor_MacroInstantiation) {
2450 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2451 return MakeMacroDefinitionCursor(Def, CXXUnit);
2452 }
2453
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002454 if (!clang_isReference(C.kind))
2455 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002456
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002457 switch (C.kind) {
2458 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002459 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002460
2461 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002462 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002463
2464 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002465 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002466
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002467 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002468 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00002469
2470 case CXCursor_TemplateRef:
2471 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2472
Ted Kremenek3064ef92010-08-27 21:34:58 +00002473 case CXCursor_CXXBaseSpecifier: {
2474 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2475 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2476 CXXUnit));
2477 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002478
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002479 default:
2480 // We would prefer to enumerate all non-reference cursor kinds here.
2481 llvm_unreachable("Unhandled reference cursor kind");
2482 break;
2483 }
2484 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002485
Douglas Gregorc5d1e932010-01-19 01:20:04 +00002486 return clang_getNullCursor();
2487}
2488
Douglas Gregorb6998662010-01-19 19:34:47 +00002489CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002490 if (clang_isInvalid(C.kind))
2491 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002492
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002493 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002494
Douglas Gregorb6998662010-01-19 19:34:47 +00002495 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00002496 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00002497 C = clang_getCursorReferenced(C);
2498 WasReference = true;
2499 }
2500
Douglas Gregorbf7efa22010-03-18 18:23:03 +00002501 if (C.kind == CXCursor_MacroInstantiation)
2502 return clang_getCursorReferenced(C);
2503
Douglas Gregorb6998662010-01-19 19:34:47 +00002504 if (!clang_isDeclaration(C.kind))
2505 return clang_getNullCursor();
2506
2507 Decl *D = getCursorDecl(C);
2508 if (!D)
2509 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002510
Douglas Gregorb6998662010-01-19 19:34:47 +00002511 switch (D->getKind()) {
2512 // Declaration kinds that don't really separate the notions of
2513 // declaration and definition.
2514 case Decl::Namespace:
2515 case Decl::Typedef:
2516 case Decl::TemplateTypeParm:
2517 case Decl::EnumConstant:
2518 case Decl::Field:
2519 case Decl::ObjCIvar:
2520 case Decl::ObjCAtDefsField:
2521 case Decl::ImplicitParam:
2522 case Decl::ParmVar:
2523 case Decl::NonTypeTemplateParm:
2524 case Decl::TemplateTemplateParm:
2525 case Decl::ObjCCategoryImpl:
2526 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00002527 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00002528 case Decl::LinkageSpec:
2529 case Decl::ObjCPropertyImpl:
2530 case Decl::FileScopeAsm:
2531 case Decl::StaticAssert:
2532 case Decl::Block:
2533 return C;
2534
2535 // Declaration kinds that don't make any sense here, but are
2536 // nonetheless harmless.
2537 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00002538 break;
2539
2540 // Declaration kinds for which the definition is not resolvable.
2541 case Decl::UnresolvedUsingTypename:
2542 case Decl::UnresolvedUsingValue:
2543 break;
2544
2545 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002546 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2547 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002548
2549 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002550 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002551
2552 case Decl::Enum:
2553 case Decl::Record:
2554 case Decl::CXXRecord:
2555 case Decl::ClassTemplateSpecialization:
2556 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00002557 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002558 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002559 return clang_getNullCursor();
2560
2561 case Decl::Function:
2562 case Decl::CXXMethod:
2563 case Decl::CXXConstructor:
2564 case Decl::CXXDestructor:
2565 case Decl::CXXConversion: {
2566 const FunctionDecl *Def = 0;
2567 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002568 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002569 return clang_getNullCursor();
2570 }
2571
2572 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00002573 // Ask the variable if it has a definition.
2574 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2575 return MakeCXCursor(Def, CXXUnit);
2576 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00002577 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002578
Douglas Gregorb6998662010-01-19 19:34:47 +00002579 case Decl::FunctionTemplate: {
2580 const FunctionDecl *Def = 0;
2581 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002582 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002583 return clang_getNullCursor();
2584 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002585
Douglas Gregorb6998662010-01-19 19:34:47 +00002586 case Decl::ClassTemplate: {
2587 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00002588 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00002589 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002590 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002591 return clang_getNullCursor();
2592 }
2593
2594 case Decl::Using: {
2595 UsingDecl *Using = cast<UsingDecl>(D);
2596 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002597 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2598 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00002599 S != SEnd; ++S) {
2600 if (Def != clang_getNullCursor()) {
2601 // FIXME: We have no way to return multiple results.
2602 return clang_getNullCursor();
2603 }
2604
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002605 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002606 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002607 }
2608
2609 return Def;
2610 }
2611
2612 case Decl::UsingShadow:
2613 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002614 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002615 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002616
2617 case Decl::ObjCMethod: {
2618 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2619 if (Method->isThisDeclarationADefinition())
2620 return C;
2621
2622 // Dig out the method definition in the associated
2623 // @implementation, if we have it.
2624 // FIXME: The ASTs should make finding the definition easier.
2625 if (ObjCInterfaceDecl *Class
2626 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2627 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2628 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2629 Method->isInstanceMethod()))
2630 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002631 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002632
2633 return clang_getNullCursor();
2634 }
2635
2636 case Decl::ObjCCategory:
2637 if (ObjCCategoryImplDecl *Impl
2638 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002639 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002640 return clang_getNullCursor();
2641
2642 case Decl::ObjCProtocol:
2643 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2644 return C;
2645 return clang_getNullCursor();
2646
2647 case Decl::ObjCInterface:
2648 // There are two notions of a "definition" for an Objective-C
2649 // class: the interface and its implementation. When we resolved a
2650 // reference to an Objective-C class, produce the @interface as
2651 // the definition; when we were provided with the interface,
2652 // produce the @implementation as the definition.
2653 if (WasReference) {
2654 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2655 return C;
2656 } else if (ObjCImplementationDecl *Impl
2657 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002658 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002659 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002660
Douglas Gregorb6998662010-01-19 19:34:47 +00002661 case Decl::ObjCProperty:
2662 // FIXME: We don't really know where to find the
2663 // ObjCPropertyImplDecls that implement this property.
2664 return clang_getNullCursor();
2665
2666 case Decl::ObjCCompatibleAlias:
2667 if (ObjCInterfaceDecl *Class
2668 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2669 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002670 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002671
Douglas Gregorb6998662010-01-19 19:34:47 +00002672 return clang_getNullCursor();
2673
2674 case Decl::ObjCForwardProtocol: {
2675 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2676 if (Forward->protocol_size() == 1)
2677 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002678 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002679 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002680
2681 // FIXME: Cannot return multiple definitions.
2682 return clang_getNullCursor();
2683 }
2684
2685 case Decl::ObjCClass: {
2686 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2687 if (Class->size() == 1) {
2688 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2689 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002690 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002691 return clang_getNullCursor();
2692 }
2693
2694 // FIXME: Cannot return multiple definitions.
2695 return clang_getNullCursor();
2696 }
2697
2698 case Decl::Friend:
2699 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002700 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002701 return clang_getNullCursor();
2702
2703 case Decl::FriendTemplate:
2704 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002705 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002706 return clang_getNullCursor();
2707 }
2708
2709 return clang_getNullCursor();
2710}
2711
2712unsigned clang_isCursorDefinition(CXCursor C) {
2713 if (!clang_isDeclaration(C.kind))
2714 return 0;
2715
2716 return clang_getCursorDefinition(C) == C;
2717}
2718
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002719void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002720 const char **startBuf,
2721 const char **endBuf,
2722 unsigned *startLine,
2723 unsigned *startColumn,
2724 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002725 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002726 assert(getCursorDecl(C) && "CXCursor has null decl");
2727 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002728 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2729 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002730
Steve Naroff4ade6d62009-09-23 17:52:52 +00002731 SourceManager &SM = FD->getASTContext().getSourceManager();
2732 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2733 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2734 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2735 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2736 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2737 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2738}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002739
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002740void clang_enableStackTraces(void) {
2741 llvm::sys::PrintStackTraceOnErrorSignal();
2742}
2743
Ted Kremenekfb480492010-01-13 21:46:36 +00002744} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002745
Ted Kremenekfb480492010-01-13 21:46:36 +00002746//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002747// Token-based Operations.
2748//===----------------------------------------------------------------------===//
2749
2750/* CXToken layout:
2751 * int_data[0]: a CXTokenKind
2752 * int_data[1]: starting token location
2753 * int_data[2]: token length
2754 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002755 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002756 * otherwise unused.
2757 */
2758extern "C" {
2759
2760CXTokenKind clang_getTokenKind(CXToken CXTok) {
2761 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2762}
2763
2764CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2765 switch (clang_getTokenKind(CXTok)) {
2766 case CXToken_Identifier:
2767 case CXToken_Keyword:
2768 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002769 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2770 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002771
2772 case CXToken_Literal: {
2773 // We have stashed the starting pointer in the ptr_data field. Use it.
2774 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002775 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002776 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002777
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002778 case CXToken_Punctuation:
2779 case CXToken_Comment:
2780 break;
2781 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002782
2783 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002784 // deconstructing the source location.
2785 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2786 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002787 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002788
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002789 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2790 std::pair<FileID, unsigned> LocInfo
2791 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002792 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002793 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002794 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2795 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002796 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002797
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002798 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002799}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002800
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002801CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2802 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2803 if (!CXXUnit)
2804 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002805
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002806 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2807 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2808}
2809
2810CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2811 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002812 if (!CXXUnit)
2813 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002814
2815 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002816 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2817}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002818
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002819void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2820 CXToken **Tokens, unsigned *NumTokens) {
2821 if (Tokens)
2822 *Tokens = 0;
2823 if (NumTokens)
2824 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002825
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002826 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2827 if (!CXXUnit || !Tokens || !NumTokens)
2828 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002829
Douglas Gregorbdf60622010-03-05 21:16:25 +00002830 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2831
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002832 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002833 if (R.isInvalid())
2834 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002835
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002836 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2837 std::pair<FileID, unsigned> BeginLocInfo
2838 = SourceMgr.getDecomposedLoc(R.getBegin());
2839 std::pair<FileID, unsigned> EndLocInfo
2840 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002841
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002842 // Cannot tokenize across files.
2843 if (BeginLocInfo.first != EndLocInfo.first)
2844 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002845
2846 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002847 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002848 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002849 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002850 if (Invalid)
2851 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002852
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002853 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2854 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002855 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002856 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002857
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002858 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002859 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002860 llvm::SmallVector<CXToken, 32> CXTokens;
2861 Token Tok;
2862 do {
2863 // Lex the next token
2864 Lex.LexFromRawLexer(Tok);
2865 if (Tok.is(tok::eof))
2866 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002867
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002868 // Initialize the CXToken.
2869 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002870
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002871 // - Common fields
2872 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2873 CXTok.int_data[2] = Tok.getLength();
2874 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002875
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002876 // - Kind-specific fields
2877 if (Tok.isLiteral()) {
2878 CXTok.int_data[0] = CXToken_Literal;
2879 CXTok.ptr_data = (void *)Tok.getLiteralData();
2880 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002881 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002882 std::pair<FileID, unsigned> LocInfo
2883 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002884 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002885 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002886 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2887 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002888 return;
2889
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002890 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002891 IdentifierInfo *II
2892 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00002893
2894 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2895 CXTok.int_data[0] = CXToken_Keyword;
2896 }
2897 else {
2898 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2899 CXToken_Identifier
2900 : CXToken_Keyword;
2901 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002902 CXTok.ptr_data = II;
2903 } else if (Tok.is(tok::comment)) {
2904 CXTok.int_data[0] = CXToken_Comment;
2905 CXTok.ptr_data = 0;
2906 } else {
2907 CXTok.int_data[0] = CXToken_Punctuation;
2908 CXTok.ptr_data = 0;
2909 }
2910 CXTokens.push_back(CXTok);
2911 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002912
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002913 if (CXTokens.empty())
2914 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002915
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002916 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2917 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2918 *NumTokens = CXTokens.size();
2919}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002920
Ted Kremenek6db61092010-05-05 00:55:15 +00002921void clang_disposeTokens(CXTranslationUnit TU,
2922 CXToken *Tokens, unsigned NumTokens) {
2923 free(Tokens);
2924}
2925
2926} // end: extern "C"
2927
2928//===----------------------------------------------------------------------===//
2929// Token annotation APIs.
2930//===----------------------------------------------------------------------===//
2931
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002932typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002933static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2934 CXCursor parent,
2935 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00002936namespace {
2937class AnnotateTokensWorker {
2938 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002939 CXToken *Tokens;
2940 CXCursor *Cursors;
2941 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002942 unsigned TokIdx;
2943 CursorVisitor AnnotateVis;
2944 SourceManager &SrcMgr;
2945
2946 bool MoreTokens() const { return TokIdx < NumTokens; }
2947 unsigned NextToken() const { return TokIdx; }
2948 void AdvanceToken() { ++TokIdx; }
2949 SourceLocation GetTokenLoc(unsigned tokI) {
2950 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2951 }
2952
Ted Kremenek6db61092010-05-05 00:55:15 +00002953public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00002954 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002955 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2956 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00002957 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002958 NumTokens(numTokens), TokIdx(0),
2959 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2960 Decl::MaxPCHLevel, RegionOfInterest),
2961 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00002962
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002963 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00002964 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002965 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00002966};
2967}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002968
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002969void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2970 // Walk the AST within the region of interest, annotating tokens
2971 // along the way.
2972 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00002973
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002974 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2975 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2976 if (Pos != Annotated.end())
2977 Cursors[I] = Pos->second;
2978 }
2979
2980 // Finish up annotating any tokens left.
2981 if (!MoreTokens())
2982 return;
2983
2984 const CXCursor &C = clang_getNullCursor();
2985 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2986 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2987 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00002988 }
2989}
2990
Ted Kremenek6db61092010-05-05 00:55:15 +00002991enum CXChildVisitResult
2992AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002993 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2994 // We can always annotate a preprocessing directive/macro instantiation.
2995 if (clang_isPreprocessing(cursor.kind)) {
2996 Annotated[Loc.int_data] = cursor;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002997 return CXChildVisit_Recurse;
2998 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00002999
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003000 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremeneka333c662010-05-12 05:29:33 +00003001
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003002 if (cursorRange.isInvalid())
3003 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003004
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003005 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3006
Ted Kremeneka333c662010-05-12 05:29:33 +00003007 // Adjust the annotated range based specific declarations.
3008 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3009 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003010 Decl *D = cxcursor::getCursorDecl(cursor);
3011 // Don't visit synthesized ObjC methods, since they have no syntatic
3012 // representation in the source.
3013 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3014 if (MD->isSynthesized())
3015 return CXChildVisit_Continue;
3016 }
3017 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00003018 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3019 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003020 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenek6bfd5332010-05-13 15:38:38 +00003021 if (TLoc.isValid() &&
3022 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00003023 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00003024 }
3025 }
3026 }
3027
Ted Kremenek3f404602010-08-14 01:14:06 +00003028 // If the location of the cursor occurs within a macro instantiation, record
3029 // the spelling location of the cursor in our annotation map. We can then
3030 // paper over the token labelings during a post-processing step to try and
3031 // get cursor mappings for tokens that are the *arguments* of a macro
3032 // instantiation.
3033 if (L.isMacroID()) {
3034 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3035 // Only invalidate the old annotation if it isn't part of a preprocessing
3036 // directive. Here we assume that the default construction of CXCursor
3037 // results in CXCursor.kind being an initialized value (i.e., 0). If
3038 // this isn't the case, we can fix by doing lookup + insertion.
3039
3040 CXCursor &oldC = Annotated[rawEncoding];
3041 if (!clang_isPreprocessing(oldC.kind))
3042 oldC = cursor;
3043 }
3044
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003045 const enum CXCursorKind K = clang_getCursorKind(parent);
3046 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00003047 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3048 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003049
3050 while (MoreTokens()) {
3051 const unsigned I = NextToken();
3052 SourceLocation TokLoc = GetTokenLoc(I);
3053 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3054 case RangeBefore:
3055 Cursors[I] = updateC;
3056 AdvanceToken();
3057 continue;
3058 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003059 case RangeOverlap:
3060 break;
3061 }
3062 break;
3063 }
3064
3065 // Visit children to get their cursor information.
3066 const unsigned BeforeChildren = NextToken();
3067 VisitChildren(cursor);
3068 const unsigned AfterChildren = NextToken();
3069
3070 // Adjust 'Last' to the last token within the extent of the cursor.
3071 while (MoreTokens()) {
3072 const unsigned I = NextToken();
3073 SourceLocation TokLoc = GetTokenLoc(I);
3074 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3075 case RangeBefore:
3076 assert(0 && "Infeasible");
3077 case RangeAfter:
3078 break;
3079 case RangeOverlap:
3080 Cursors[I] = updateC;
3081 AdvanceToken();
3082 continue;
3083 }
3084 break;
3085 }
3086 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00003087
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003088 // Scan the tokens that are at the beginning of the cursor, but are not
3089 // capture by the child cursors.
3090
3091 // For AST elements within macros, rely on a post-annotate pass to
3092 // to correctly annotate the tokens with cursors. Otherwise we can
3093 // get confusing results of having tokens that map to cursors that really
3094 // are expanded by an instantiation.
3095 if (L.isMacroID())
3096 cursor = clang_getNullCursor();
3097
3098 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3099 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3100 break;
3101 Cursors[I] = cursor;
3102 }
3103 // Scan the tokens that are at the end of the cursor, but are not captured
3104 // but the child cursors.
3105 for (unsigned I = AfterChildren; I != Last; ++I)
3106 Cursors[I] = cursor;
3107
3108 TokIdx = Last;
3109 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003110}
3111
Ted Kremenek6db61092010-05-05 00:55:15 +00003112static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3113 CXCursor parent,
3114 CXClientData client_data) {
3115 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3116}
3117
3118extern "C" {
3119
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003120void clang_annotateTokens(CXTranslationUnit TU,
3121 CXToken *Tokens, unsigned NumTokens,
3122 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003123
3124 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003125 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003126
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003127 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003128 if (!CXXUnit) {
3129 // Any token we don't specifically annotate will have a NULL cursor.
3130 const CXCursor &C = clang_getNullCursor();
3131 for (unsigned I = 0; I != NumTokens; ++I)
3132 Cursors[I] = C;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003133 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003134 }
3135
Douglas Gregorbdf60622010-03-05 21:16:25 +00003136 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003137
Douglas Gregor0396f462010-03-19 05:22:59 +00003138 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003139 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003140 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3141 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003142 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3143 clang_getTokenLocation(TU,
3144 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003145
Douglas Gregor0396f462010-03-19 05:22:59 +00003146 // A mapping from the source locations found when re-lexing or traversing the
3147 // region of interest to the corresponding cursors.
3148 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003149
3150 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00003151 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003152 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3153 std::pair<FileID, unsigned> BeginLocInfo
3154 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3155 std::pair<FileID, unsigned> EndLocInfo
3156 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003157
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003158 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00003159 bool Invalid = false;
3160 if (BeginLocInfo.first == EndLocInfo.first &&
3161 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3162 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003163 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3164 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003165 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003166 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003167 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003168
3169 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003170 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00003171 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003172 Token Tok;
3173 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003174
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003175 reprocess:
3176 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3177 // We have found a preprocessing directive. Gobble it up so that we
3178 // don't see it while preprocessing these tokens later, but keep track of
3179 // all of the token locations inside this preprocessing directive so that
3180 // we can annotate them appropriately.
3181 //
3182 // FIXME: Some simple tests here could identify macro definitions and
3183 // #undefs, to provide specific cursor kinds for those.
3184 std::vector<SourceLocation> Locations;
3185 do {
3186 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003187 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003188 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003189
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003190 using namespace cxcursor;
3191 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003192 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3193 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00003194 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003195 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3196 Annotated[Locations[I].getRawEncoding()] = Cursor;
3197 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003198
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003199 if (Tok.isAtStartOfLine())
3200 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003201
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003202 continue;
3203 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003204
Douglas Gregor48072312010-03-18 15:23:44 +00003205 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003206 break;
3207 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003208 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003209
Douglas Gregor0396f462010-03-19 05:22:59 +00003210 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003211 // a specific cursor.
3212 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3213 CXXUnit, RegionOfInterest);
3214 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003215}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003216} // end: extern "C"
3217
3218//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00003219// Operations for querying linkage of a cursor.
3220//===----------------------------------------------------------------------===//
3221
3222extern "C" {
3223CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00003224 if (!clang_isDeclaration(cursor.kind))
3225 return CXLinkage_Invalid;
3226
Ted Kremenek16b42592010-03-03 06:36:57 +00003227 Decl *D = cxcursor::getCursorDecl(cursor);
3228 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3229 switch (ND->getLinkage()) {
3230 case NoLinkage: return CXLinkage_NoLinkage;
3231 case InternalLinkage: return CXLinkage_Internal;
3232 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3233 case ExternalLinkage: return CXLinkage_External;
3234 };
3235
3236 return CXLinkage_Invalid;
3237}
3238} // end: extern "C"
3239
3240//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003241// Operations for querying language of a cursor.
3242//===----------------------------------------------------------------------===//
3243
3244static CXLanguageKind getDeclLanguage(const Decl *D) {
3245 switch (D->getKind()) {
3246 default:
3247 break;
3248 case Decl::ImplicitParam:
3249 case Decl::ObjCAtDefsField:
3250 case Decl::ObjCCategory:
3251 case Decl::ObjCCategoryImpl:
3252 case Decl::ObjCClass:
3253 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003254 case Decl::ObjCForwardProtocol:
3255 case Decl::ObjCImplementation:
3256 case Decl::ObjCInterface:
3257 case Decl::ObjCIvar:
3258 case Decl::ObjCMethod:
3259 case Decl::ObjCProperty:
3260 case Decl::ObjCPropertyImpl:
3261 case Decl::ObjCProtocol:
3262 return CXLanguage_ObjC;
3263 case Decl::CXXConstructor:
3264 case Decl::CXXConversion:
3265 case Decl::CXXDestructor:
3266 case Decl::CXXMethod:
3267 case Decl::CXXRecord:
3268 case Decl::ClassTemplate:
3269 case Decl::ClassTemplatePartialSpecialization:
3270 case Decl::ClassTemplateSpecialization:
3271 case Decl::Friend:
3272 case Decl::FriendTemplate:
3273 case Decl::FunctionTemplate:
3274 case Decl::LinkageSpec:
3275 case Decl::Namespace:
3276 case Decl::NamespaceAlias:
3277 case Decl::NonTypeTemplateParm:
3278 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003279 case Decl::TemplateTemplateParm:
3280 case Decl::TemplateTypeParm:
3281 case Decl::UnresolvedUsingTypename:
3282 case Decl::UnresolvedUsingValue:
3283 case Decl::Using:
3284 case Decl::UsingDirective:
3285 case Decl::UsingShadow:
3286 return CXLanguage_CPlusPlus;
3287 }
3288
3289 return CXLanguage_C;
3290}
3291
3292extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00003293
3294enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3295 if (clang_isDeclaration(cursor.kind))
3296 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3297 if (D->hasAttr<UnavailableAttr>() ||
3298 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3299 return CXAvailability_Available;
3300
3301 if (D->hasAttr<DeprecatedAttr>())
3302 return CXAvailability_Deprecated;
3303 }
3304
3305 return CXAvailability_Available;
3306}
3307
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003308CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3309 if (clang_isDeclaration(cursor.kind))
3310 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3311
3312 return CXLanguage_Invalid;
3313}
3314} // end: extern "C"
3315
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003316
3317//===----------------------------------------------------------------------===//
3318// C++ AST instrospection.
3319//===----------------------------------------------------------------------===//
3320
3321extern "C" {
3322unsigned clang_CXXMethod_isStatic(CXCursor C) {
3323 if (!clang_isDeclaration(C.kind))
3324 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00003325
3326 CXXMethodDecl *Method = 0;
3327 Decl *D = cxcursor::getCursorDecl(C);
3328 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3329 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3330 else
3331 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3332 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00003333}
Ted Kremenekb12903e2010-05-18 22:32:15 +00003334
Ted Kremenek9ada39a2010-05-17 20:06:56 +00003335} // end: extern "C"
3336
Ted Kremenek45e1dae2010-04-12 21:22:16 +00003337//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00003338// Attribute introspection.
3339//===----------------------------------------------------------------------===//
3340
3341extern "C" {
3342CXType clang_getIBOutletCollectionType(CXCursor C) {
3343 if (C.kind != CXCursor_IBOutletCollectionAttr)
3344 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3345
3346 IBOutletCollectionAttr *A =
3347 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3348
3349 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3350}
3351} // end: extern "C"
3352
3353//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00003354// CXString Operations.
3355//===----------------------------------------------------------------------===//
3356
3357extern "C" {
3358const char *clang_getCString(CXString string) {
3359 return string.Spelling;
3360}
3361
3362void clang_disposeString(CXString string) {
3363 if (string.MustFreeString && string.Spelling)
3364 free((void*)string.Spelling);
3365}
Ted Kremenek04bb7162010-01-22 22:44:15 +00003366
Ted Kremenekfb480492010-01-13 21:46:36 +00003367} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00003368
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003369namespace clang { namespace cxstring {
3370CXString createCXString(const char *String, bool DupString){
3371 CXString Str;
3372 if (DupString) {
3373 Str.Spelling = strdup(String);
3374 Str.MustFreeString = 1;
3375 } else {
3376 Str.Spelling = String;
3377 Str.MustFreeString = 0;
3378 }
3379 return Str;
3380}
3381
3382CXString createCXString(llvm::StringRef String, bool DupString) {
3383 CXString Result;
3384 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3385 char *Spelling = (char *)malloc(String.size() + 1);
3386 memmove(Spelling, String.data(), String.size());
3387 Spelling[String.size()] = 0;
3388 Result.Spelling = Spelling;
3389 Result.MustFreeString = 1;
3390 } else {
3391 Result.Spelling = String.data();
3392 Result.MustFreeString = 0;
3393 }
3394 return Result;
3395}
3396}}
3397
Ted Kremenek04bb7162010-01-22 22:44:15 +00003398//===----------------------------------------------------------------------===//
3399// Misc. utility functions.
3400//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003401
Ted Kremenek04bb7162010-01-22 22:44:15 +00003402extern "C" {
3403
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00003404CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003405 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00003406}
3407
3408} // end: extern "C"