blob: c51ca7f1190d86ed99599a0ebd54f8b2360d4959 [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 Kremeneka297de22010-01-25 22:34:44 +000017#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000018#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000019
Ted Kremenek04bb7162010-01-22 22:44:15 +000020#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000021
Steve Naroff50398192009-08-28 15:28:48 +000022#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000024#include "clang/AST/TypeLocVisitor.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000026#include "clang/Lex/Lexer.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000027#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000028#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000029#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000030#include "llvm/System/Signals.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000031
Benjamin Kramerc2a98162010-03-13 21:22:49 +000032// Needed to define L_TMPNAM on some systems.
33#include <cstdio>
34
Steve Naroff50398192009-08-28 15:28:48 +000035using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000036using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000037using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000038using namespace idx;
39
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000040//===----------------------------------------------------------------------===//
41// Crash Reporting.
42//===----------------------------------------------------------------------===//
43
44#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000045#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000046#include "clang/Analysis/Support/SaveAndRestore.h"
47// Integrate with crash reporter.
48extern "C" const char *__crashreporter_info__;
Ted Kremenek6b569992010-02-17 21:12:23 +000049#define NUM_CRASH_STRINGS 32
Ted Kremenek29b72842010-01-07 22:49:05 +000050static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000051static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000052static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
53static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
54
55static unsigned SetCrashTracerInfo(const char *str,
56 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Ted Kremenek254ba7c2010-01-07 23:13:53 +000058 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000059 while (crashtracer_strings[slot]) {
60 if (++slot == NUM_CRASH_STRINGS)
61 slot = 0;
62 }
63 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000064 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000065
66 // We need to create an aggregate string because multiple threads
67 // may be in this method at one time. The crash reporter string
68 // will attempt to overapproximate the set of in-flight invocations
69 // of this function. Race conditions can still cause this goal
70 // to not be achieved.
71 {
Ted Kremenekf0e23e82010-02-17 00:41:40 +000072 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek29b72842010-01-07 22:49:05 +000073 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
74 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
75 }
76 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
77 return slot;
78}
79
80static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000081 unsigned max_slot = 0;
82 unsigned max_value = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +000083
Ted Kremenek254ba7c2010-01-07 23:13:53 +000084 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
85
86 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
87 if (agg_crashtracer_strings[i] &&
88 crashtracer_counter_id[i] > max_value) {
89 max_slot = i;
90 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000091 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000092
93 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000094}
95
96namespace {
97class ArgsCrashTracerInfo {
98 llvm::SmallString<1024> CrashString;
99 llvm::SmallString<1024> AggregateString;
100 unsigned crashtracerSlot;
101public:
102 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
103 : crashtracerSlot(0)
104 {
105 {
106 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenek0baa9522010-03-05 22:43:25 +0000107 Out << "ClangCIndex [" << getClangFullVersion() << "]"
108 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek29b72842010-01-07 22:49:05 +0000109 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
110 E=Args.end(); I!=E; ++I)
111 Out << ' ' << *I;
112 }
113 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
114 AggregateString);
115 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000116
Ted Kremenek29b72842010-01-07 22:49:05 +0000117 ~ArgsCrashTracerInfo() {
118 ResetCrashTracerInfo(crashtracerSlot);
119 }
120};
121}
122#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000124/// \brief The result of comparing two source ranges.
125enum RangeComparisonResult {
126 /// \brief Either the ranges overlap or one of the ranges is invalid.
127 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000128
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000129 /// \brief The first range ends before the second range starts.
130 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000131
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132 /// \brief The first range starts after the second range ends.
133 RangeAfter
134};
135
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000136/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000137/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000138static RangeComparisonResult RangeCompare(SourceManager &SM,
139 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000140 SourceRange R2) {
141 assert(R1.isValid() && "First range is invalid?");
142 assert(R2.isValid() && "Second range is invalid?");
Daniel Dunbard52864b2010-02-14 10:02:57 +0000143 if (R1.getEnd() == R2.getBegin() ||
144 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000145 return RangeBefore;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000146 if (R2.getEnd() == R1.getBegin() ||
147 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000148 return RangeAfter;
149 return RangeOverlap;
150}
151
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000152/// \brief Translate a Clang source range into a CIndex source range.
153///
154/// Clang internally represents ranges where the end location points to the
155/// start of the token at the end. However, for external clients it is more
156/// useful to have a CXSourceRange be a proper half-open interval. This routine
157/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000158CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000159 const LangOptions &LangOpts,
160 SourceRange R) {
161 // FIXME: This is largely copy-paste from
162 // TextDiagnosticPrinter::HighlightRange. When it is clear that this is what
163 // we want the two routines should be refactored.
164
165 // We want the last character in this location, so we will adjust the
166 // instantiation location accordingly.
167
168 // If the location is from a macro instantiation, get the end of the
169 // instantiation range.
170 SourceLocation EndLoc = R.getEnd();
171 SourceLocation InstLoc = SM.getInstantiationLoc(EndLoc);
172 if (EndLoc.isMacroID())
173 InstLoc = SM.getInstantiationRange(EndLoc).second;
174
175 // Measure the length token we're pointing at, so we can adjust the physical
176 // location in the file to point at the last character.
177 //
178 // FIXME: This won't cope with trigraphs or escaped newlines well. For that,
179 // we actually need a preprocessor, which isn't currently available
180 // here. Eventually, we'll switch the pointer data of
181 // CXSourceLocation/CXSourceRange to a translation unit (CXXUnit), so that the
182 // preprocessor will be available here. At that point, we can use
183 // Preprocessor::getLocForEndOfToken().
184 if (InstLoc.isValid()) {
185 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000186 EndLoc = EndLoc.getFileLocWithOffset(Length);
187 }
188
189 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
190 R.getBegin().getRawEncoding(),
191 EndLoc.getRawEncoding() };
192 return Result;
193}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000194
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000195//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000196// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000197//===----------------------------------------------------------------------===//
198
Steve Naroff89922f82009-08-31 00:59:03 +0000199namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000200
Douglas Gregorb1373d02010-01-20 20:59:29 +0000201// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000202class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000203 public TypeLocVisitor<CursorVisitor, bool>,
204 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000205{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000206 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000207 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000208
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000209 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000210 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000211
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000212 /// \brief The declaration that serves at the parent of any statement or
213 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000214 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000215
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000216 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000217 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000218
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000219 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000221
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000222 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
223 // to the visitor. Declarations with a PCH level greater than this value will
224 // be suppressed.
225 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000226
227 /// \brief When valid, a source range to which the cursor should restrict
228 /// its search.
229 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000230
Douglas Gregorb1373d02010-01-20 20:59:29 +0000231 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000232 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000233 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000234
235 /// \brief Determine whether this particular source range comes before, comes
236 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000237 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000238 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000239 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
240
Steve Naroff89922f82009-08-31 00:59:03 +0000241public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000242 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
243 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000244 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000245 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000246 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000247 {
248 Parent.kind = CXCursor_NoDeclFound;
249 Parent.data[0] = 0;
250 Parent.data[1] = 0;
251 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000252 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000253 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000254
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000255 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000256 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000257
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000258 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000259 bool VisitAttributes(Decl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000260 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000261 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
262 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000263 bool VisitTagDecl(TagDecl *D);
264 bool VisitEnumConstantDecl(EnumConstantDecl *D);
265 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
266 bool VisitFunctionDecl(FunctionDecl *ND);
267 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000268 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000269 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
270 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
271 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
272 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
273 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
274 bool VisitObjCImplDecl(ObjCImplDecl *D);
275 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
276 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
277 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
278 // etc.
279 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
280 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
281 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000282
283 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000284 // FIXME: QualifiedTypeLoc doesn't provide any location information
285 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000286 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000287 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
288 bool VisitTagTypeLoc(TagTypeLoc TL);
289 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
290 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
291 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
292 bool VisitPointerTypeLoc(PointerTypeLoc TL);
293 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
294 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
295 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
296 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
297 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
298 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000299 // FIXME: Implement for TemplateSpecializationTypeLoc
300 // FIXME: Implement visitors here when the unimplemented TypeLocs get
301 // implemented
302 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
303 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000304
Douglas Gregora59e3902010-01-21 23:27:09 +0000305 // Statement visitors
306 bool VisitStmt(Stmt *S);
307 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000308 // FIXME: LabelStmt label?
309 bool VisitIfStmt(IfStmt *S);
310 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000311 bool VisitWhileStmt(WhileStmt *S);
312 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000313
Douglas Gregor336fd812010-01-23 00:40:08 +0000314 // Expression visitors
315 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
316 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
317 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000318 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000319};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000320
Ted Kremenekab188932010-01-05 19:32:54 +0000321} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000322
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000323RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000324 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
325}
326
Douglas Gregorb1373d02010-01-20 20:59:29 +0000327/// \brief Visit the given cursor and, if requested by the visitor,
328/// its children.
329///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000330/// \param Cursor the cursor to visit.
331///
332/// \param CheckRegionOfInterest if true, then the caller already checked that
333/// this cursor is within the region of interest.
334///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000335/// \returns true if the visitation should be aborted, false if it
336/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000337bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000338 if (clang_isInvalid(Cursor.kind))
339 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000340
Douglas Gregorb1373d02010-01-20 20:59:29 +0000341 if (clang_isDeclaration(Cursor.kind)) {
342 Decl *D = getCursorDecl(Cursor);
343 assert(D && "Invalid declaration cursor");
344 if (D->getPCHLevel() > MaxPCHLevel)
345 return false;
346
347 if (D->isImplicit())
348 return false;
349 }
350
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000351 // If we have a range of interest, and this cursor doesn't intersect with it,
352 // we're done.
353 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000354 SourceRange Range =
355 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
356 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000357 return false;
358 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000359
Douglas Gregorb1373d02010-01-20 20:59:29 +0000360 switch (Visitor(Cursor, Parent, ClientData)) {
361 case CXChildVisit_Break:
362 return true;
363
364 case CXChildVisit_Continue:
365 return false;
366
367 case CXChildVisit_Recurse:
368 return VisitChildren(Cursor);
369 }
370
Douglas Gregorfd643772010-01-25 16:45:46 +0000371 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372}
373
374/// \brief Visit the children of the given cursor.
375///
376/// \returns true if the visitation should be aborted, false if it
377/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000378bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000379 if (clang_isReference(Cursor.kind)) {
380 // By definition, references have no children.
381 return false;
382 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000383
384 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000385 // done.
386 class SetParentRAII {
387 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000388 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000389 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000390
Douglas Gregorb1373d02010-01-20 20:59:29 +0000391 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000392 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000393 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000394 {
395 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000396 if (clang_isDeclaration(Parent.kind))
397 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000398 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000399
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400 ~SetParentRAII() {
401 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000402 if (clang_isDeclaration(Parent.kind))
403 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000404 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000405 } SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000406
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407 if (clang_isDeclaration(Cursor.kind)) {
408 Decl *D = getCursorDecl(Cursor);
409 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000410 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000411 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000412
Douglas Gregora59e3902010-01-21 23:27:09 +0000413 if (clang_isStatement(Cursor.kind))
414 return Visit(getCursorStmt(Cursor));
415 if (clang_isExpression(Cursor.kind))
416 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000417
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000419 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000420 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
421 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000422 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
423 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
424 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000425 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000426 return true;
427 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000428 } else if (VisitDeclContext(
429 CXXUnit->getASTContext().getTranslationUnitDecl()))
430 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000431
Douglas Gregor0396f462010-03-19 05:22:59 +0000432 // Walk the preprocessing record.
433 if (CXXUnit->hasPreprocessingRecord()) {
434 // FIXME: Once we have the ability to deserialize a preprocessing record,
435 // do so.
436 PreprocessingRecord &PPRec = CXXUnit->getPreprocessingRecord();
437 for (PreprocessingRecord::iterator E = PPRec.begin(), EEnd = PPRec.end();
438 E != EEnd; ++E) {
439 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
440 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
441 return true;
442 continue;
443 }
444
445 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
446 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
447 return true;
448
449 continue;
450 }
451 }
452 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000453 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000454 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000455
Douglas Gregorb1373d02010-01-20 20:59:29 +0000456 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000457 return false;
458}
459
Douglas Gregorb1373d02010-01-20 20:59:29 +0000460bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000461 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000462 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000463
Daniel Dunbard52864b2010-02-14 10:02:57 +0000464 CXCursor Cursor = MakeCXCursor(*I, TU);
465
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000466 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000467 SourceRange Range =
468 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
469 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000470 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000471
472 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000473 case RangeBefore:
474 // This declaration comes before the region of interest; skip it.
475 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000476
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000477 case RangeAfter:
478 // This declaration comes after the region of interest; we're done.
479 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000480
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000481 case RangeOverlap:
482 // This declaration overlaps the region of interest; visit it.
483 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000484 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000485 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000486
Daniel Dunbard52864b2010-02-14 10:02:57 +0000487 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000488 return true;
489 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000490
Douglas Gregorb1373d02010-01-20 20:59:29 +0000491 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000492}
493
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000494bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
495 llvm_unreachable("Translation units are visited directly by Visit()");
496 return false;
497}
498
499bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
500 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
501 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000502
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000503 return false;
504}
505
506bool CursorVisitor::VisitTagDecl(TagDecl *D) {
507 return VisitDeclContext(D);
508}
509
510bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
511 if (Expr *Init = D->getInitExpr())
512 return Visit(MakeCXCursor(Init, StmtParent, TU));
513 return false;
514}
515
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000516bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
517 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
518 if (Visit(TSInfo->getTypeLoc()))
519 return true;
520
521 return false;
522}
523
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000525 if (VisitDeclaratorDecl(ND))
526 return true;
527
Douglas Gregora59e3902010-01-21 23:27:09 +0000528 if (ND->isThisDeclarationADefinition() &&
529 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
530 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000531
Douglas Gregorb1373d02010-01-20 20:59:29 +0000532 return false;
533}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000534
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000535bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
536 if (VisitDeclaratorDecl(D))
537 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000538
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000539 if (Expr *BitWidth = D->getBitWidth())
540 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000541
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000542 return false;
543}
544
545bool CursorVisitor::VisitVarDecl(VarDecl *D) {
546 if (VisitDeclaratorDecl(D))
547 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000548
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000549 if (Expr *Init = D->getInit())
550 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000551
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000552 return false;
553}
554
555bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000556 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
557 if (Visit(TSInfo->getTypeLoc()))
558 return true;
559
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000560 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000561 PEnd = ND->param_end();
562 P != PEnd; ++P) {
563 if (Visit(MakeCXCursor(*P, TU)))
564 return true;
565 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000566
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000567 if (ND->isThisDeclarationADefinition() &&
568 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
569 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000570
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000571 return false;
572}
573
Douglas Gregora59e3902010-01-21 23:27:09 +0000574bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
575 return VisitDeclContext(D);
576}
577
Douglas Gregorb1373d02010-01-20 20:59:29 +0000578bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000579 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
580 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000581 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000582
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000583 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
584 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
585 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000586 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000587 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000588
Douglas Gregora59e3902010-01-21 23:27:09 +0000589 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000590}
591
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000592bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
593 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
594 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
595 E = PID->protocol_end(); I != E; ++I, ++PL)
596 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
597 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599 return VisitObjCContainerDecl(PID);
600}
601
Douglas Gregorb1373d02010-01-20 20:59:29 +0000602bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000603 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000604 if (D->getSuperClass() &&
605 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000606 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000607 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000608 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000609
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000610 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
611 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
612 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000613 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000614 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000615
Douglas Gregora59e3902010-01-21 23:27:09 +0000616 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000617}
618
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000619bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
620 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000621}
622
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000623bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000624 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000625 D->getLocation(), TU)))
626 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000627
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000628 return VisitObjCImplDecl(D);
629}
630
631bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
632#if 0
633 // Issue callbacks for super class.
634 // FIXME: No source location information!
635 if (D->getSuperClass() &&
636 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000637 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000638 TU)))
639 return true;
640#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000641
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000642 return VisitObjCImplDecl(D);
643}
644
645bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
646 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
647 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
648 E = D->protocol_end();
649 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000650 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000651 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000652
653 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000654}
655
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000656bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
657 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
658 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
659 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000660
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000661 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000662}
663
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000664bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
665 ASTContext &Context = TU->getASTContext();
666
667 // Some builtin types (such as Objective-C's "id", "sel", and
668 // "Class") have associated declarations. Create cursors for those.
669 QualType VisitType;
670 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000671 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000672 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000673 case BuiltinType::Char_U:
674 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000675 case BuiltinType::Char16:
676 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000677 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000678 case BuiltinType::UInt:
679 case BuiltinType::ULong:
680 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000681 case BuiltinType::UInt128:
682 case BuiltinType::Char_S:
683 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000684 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000685 case BuiltinType::Short:
686 case BuiltinType::Int:
687 case BuiltinType::Long:
688 case BuiltinType::LongLong:
689 case BuiltinType::Int128:
690 case BuiltinType::Float:
691 case BuiltinType::Double:
692 case BuiltinType::LongDouble:
693 case BuiltinType::NullPtr:
694 case BuiltinType::Overload:
695 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000696 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000697
698 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000699 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000700
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000701 case BuiltinType::ObjCId:
702 VisitType = Context.getObjCIdType();
703 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000704
705 case BuiltinType::ObjCClass:
706 VisitType = Context.getObjCClassType();
707 break;
708
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000709 case BuiltinType::ObjCSel:
710 VisitType = Context.getObjCSelType();
711 break;
712 }
713
714 if (!VisitType.isNull()) {
715 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000716 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000717 TU));
718 }
719
720 return false;
721}
722
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000723bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
724 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
725}
726
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000727bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
728 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
729}
730
731bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
732 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
733}
734
735bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
736 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
737 return true;
738
739 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
740 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
741 TU)))
742 return true;
743 }
744
745 return false;
746}
747
748bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
749 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
750 return true;
751
752 if (TL.hasProtocolsAsWritten()) {
753 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000754 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000755 TL.getProtocolLoc(I),
756 TU)))
757 return true;
758 }
759 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000760
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000761 return false;
762}
763
764bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
765 return Visit(TL.getPointeeLoc());
766}
767
768bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
769 return Visit(TL.getPointeeLoc());
770}
771
772bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
773 return Visit(TL.getPointeeLoc());
774}
775
776bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000777 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000778}
779
780bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000781 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000782}
783
784bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
785 if (Visit(TL.getResultLoc()))
786 return true;
787
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000788 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
789 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
790 return true;
791
792 return false;
793}
794
795bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
796 if (Visit(TL.getElementLoc()))
797 return true;
798
799 if (Expr *Size = TL.getSizeExpr())
800 return Visit(MakeCXCursor(Size, StmtParent, TU));
801
802 return false;
803}
804
Douglas Gregor2332c112010-01-21 20:48:56 +0000805bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
806 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
807}
808
809bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
810 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
811 return Visit(TSInfo->getTypeLoc());
812
813 return false;
814}
815
Douglas Gregora59e3902010-01-21 23:27:09 +0000816bool CursorVisitor::VisitStmt(Stmt *S) {
817 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
818 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000819 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000820 return true;
821 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000822
Douglas Gregora59e3902010-01-21 23:27:09 +0000823 return false;
824}
825
826bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
827 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
828 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000829 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000830 return true;
831 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000832
Douglas Gregora59e3902010-01-21 23:27:09 +0000833 return false;
834}
835
Douglas Gregorf5bab412010-01-22 01:00:11 +0000836bool CursorVisitor::VisitIfStmt(IfStmt *S) {
837 if (VarDecl *Var = S->getConditionVariable()) {
838 if (Visit(MakeCXCursor(Var, TU)))
839 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000840 }
841
Douglas Gregor263b47b2010-01-25 16:12:32 +0000842 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
843 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000844 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
845 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000846 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
847 return true;
848
849 return false;
850}
851
852bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
853 if (VarDecl *Var = S->getConditionVariable()) {
854 if (Visit(MakeCXCursor(Var, TU)))
855 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000856 }
857
Douglas Gregor263b47b2010-01-25 16:12:32 +0000858 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
859 return true;
860 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
861 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000862
Douglas Gregor263b47b2010-01-25 16:12:32 +0000863 return false;
864}
865
866bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
867 if (VarDecl *Var = S->getConditionVariable()) {
868 if (Visit(MakeCXCursor(Var, TU)))
869 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000870 }
871
Douglas Gregor263b47b2010-01-25 16:12:32 +0000872 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
873 return true;
874 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000875 return true;
876
Douglas Gregor263b47b2010-01-25 16:12:32 +0000877 return false;
878}
879
880bool CursorVisitor::VisitForStmt(ForStmt *S) {
881 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
882 return true;
883 if (VarDecl *Var = S->getConditionVariable()) {
884 if (Visit(MakeCXCursor(Var, TU)))
885 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000886 }
887
Douglas Gregor263b47b2010-01-25 16:12:32 +0000888 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
889 return true;
890 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
891 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000892 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
893 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000894
Douglas Gregorf5bab412010-01-22 01:00:11 +0000895 return false;
896}
897
Douglas Gregor336fd812010-01-23 00:40:08 +0000898bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
899 if (E->isArgumentType()) {
900 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
901 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000902
Douglas Gregor336fd812010-01-23 00:40:08 +0000903 return false;
904 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000905
Douglas Gregor336fd812010-01-23 00:40:08 +0000906 return VisitExpr(E);
907}
908
909bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
910 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
911 if (Visit(TSInfo->getTypeLoc()))
912 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000913
Douglas Gregor336fd812010-01-23 00:40:08 +0000914 return VisitCastExpr(E);
915}
916
917bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
918 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
919 if (Visit(TSInfo->getTypeLoc()))
920 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000921
Douglas Gregor336fd812010-01-23 00:40:08 +0000922 return VisitExpr(E);
923}
924
Douglas Gregorc2350e52010-03-08 16:40:19 +0000925bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
926 ObjCMessageExpr::ClassInfo CI = E->getClassInfo();
927 if (CI.Decl && Visit(MakeCursorObjCClassRef(CI.Decl, CI.Loc, TU)))
928 return true;
929
930 return VisitExpr(E);
931}
932
Ted Kremenek09dfa372010-02-18 05:46:33 +0000933bool CursorVisitor::VisitAttributes(Decl *D) {
934 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
935 if (Visit(MakeCXCursor(A, D, TU)))
936 return true;
937
938 return false;
939}
940
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000941extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000942CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
943 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000944 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000945 if (excludeDeclarationsFromPCH)
946 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000947 if (displayDiagnostics)
948 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000949 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000950}
951
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000952void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000953 if (CIdx)
954 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000955}
956
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000957void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000958 if (CIdx) {
959 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
960 CXXIdx->setUseExternalASTGeneration(value);
961 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000962}
963
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000964CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +0000965 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000966 if (!CIdx)
967 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000968
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000969 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000970
Douglas Gregor5352ac02010-01-28 00:27:43 +0000971 // Configure the diagnostics.
972 DiagnosticOptions DiagOpts;
973 llvm::OwningPtr<Diagnostic> Diags;
974 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Douglas Gregor5352ac02010-01-28 00:27:43 +0000975 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +0000976 CXXIdx->getOnlyLocalDecls(),
977 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +0000978}
979
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000980CXTranslationUnit
981clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
982 const char *source_filename,
983 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000984 const char **command_line_args,
985 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +0000986 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000987 if (!CIdx)
988 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000989
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000990 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
991
Douglas Gregor5352ac02010-01-28 00:27:43 +0000992 // Configure the diagnostics.
993 DiagnosticOptions DiagOpts;
994 llvm::OwningPtr<Diagnostic> Diags;
995 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000996
Douglas Gregor4db64a42010-01-23 00:14:00 +0000997 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
998 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000999 const llvm::MemoryBuffer *Buffer
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +00001000 = llvm::MemoryBuffer::getMemBufferCopy(unsaved_files[I].Contents,
Douglas Gregor313e26c2010-02-18 23:35:40 +00001001 unsaved_files[I].Contents + unsaved_files[I].Length,
1002 unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001003 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1004 Buffer));
1005 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001006
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001007 if (!CXXIdx->getUseExternalASTGeneration()) {
1008 llvm::SmallVector<const char *, 16> Args;
1009
1010 // The 'source_filename' argument is optional. If the caller does not
1011 // specify it then it is assumed that the source file is specified
1012 // in the actual argument list.
1013 if (source_filename)
1014 Args.push_back(source_filename);
1015 Args.insert(Args.end(), command_line_args,
1016 command_line_args + num_command_line_args);
1017
Douglas Gregor5352ac02010-01-28 00:27:43 +00001018 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001019
Ted Kremenek29b72842010-01-07 22:49:05 +00001020#ifdef USE_CRASHTRACER
1021 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001022#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001023
Daniel Dunbar94220972009-12-05 02:17:18 +00001024 llvm::OwningPtr<ASTUnit> Unit(
1025 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001026 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001027 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001028 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001029 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001030 RemappedFiles.size(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001031 /*CaptureDiagnostics=*/true,
1032 /*WantPreprocessingRecord=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001033
Daniel Dunbar94220972009-12-05 02:17:18 +00001034 // FIXME: Until we have broader testing, just drop the entire AST if we
1035 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001036 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001037 // Make sure to check that 'Unit' is non-NULL.
1038 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001039 for (ASTUnit::diag_iterator D = Unit->diag_begin(),
1040 DEnd = Unit->diag_end();
1041 D != DEnd; ++D) {
1042 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001043 CXString Msg = clang_formatDiagnostic(&Diag,
1044 clang_defaultDiagnosticDisplayOptions());
1045 fprintf(stderr, "%s\n", clang_getCString(Msg));
1046 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001047 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001048#ifdef LLVM_ON_WIN32
1049 // On Windows, force a flush, since there may be multiple copies of
1050 // stderr and stdout in the file system, all with different buffers
1051 // but writing to the same device.
1052 fflush(stderr);
1053#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001054 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001055 return 0;
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001056 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001057
1058 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001059 }
1060
Ted Kremenek139ba862009-10-22 00:03:57 +00001061 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001062 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001063
Ted Kremenek139ba862009-10-22 00:03:57 +00001064 // First add the complete path to the 'clang' executable.
1065 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001066 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001067
Ted Kremenek139ba862009-10-22 00:03:57 +00001068 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001069 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001070
Ted Kremenek139ba862009-10-22 00:03:57 +00001071 // The 'source_filename' argument is optional. If the caller does not
1072 // specify it then it is assumed that the source file is specified
1073 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001074 if (source_filename)
1075 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001076
Steve Naroff37b5ac22009-10-15 20:50:09 +00001077 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001078 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001079 char astTmpFile[L_tmpnam];
1080 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001081
Douglas Gregor4db64a42010-01-23 00:14:00 +00001082 // Remap any unsaved files to temporary files.
1083 std::vector<llvm::sys::Path> TemporaryFiles;
1084 std::vector<std::string> RemapArgs;
1085 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1086 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001087
Douglas Gregor4db64a42010-01-23 00:14:00 +00001088 // The pointers into the elements of RemapArgs are stable because we
1089 // won't be adding anything to RemapArgs after this point.
1090 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1091 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001092
Ted Kremenek139ba862009-10-22 00:03:57 +00001093 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1094 for (int i = 0; i < num_command_line_args; ++i)
1095 if (const char *arg = command_line_args[i]) {
1096 if (strcmp(arg, "-o") == 0) {
1097 ++i; // Also skip the matching argument.
1098 continue;
1099 }
1100 if (strcmp(arg, "-emit-ast") == 0 ||
1101 strcmp(arg, "-c") == 0 ||
1102 strcmp(arg, "-fsyntax-only") == 0) {
1103 continue;
1104 }
1105
1106 // Keep the argument.
1107 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001108 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001109
Douglas Gregord93256e2010-01-28 06:00:51 +00001110 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001111 char tmpFileResults[L_tmpnam];
1112 char *tmpResultsFileName = tmpnam(tmpFileResults);
1113 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001114 TemporaryFiles.push_back(DiagnosticsFile);
1115 argv.push_back("-fdiagnostics-binary");
1116
Ted Kremenek139ba862009-10-22 00:03:57 +00001117 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001118 argv.push_back(NULL);
1119
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001120 // Invoke 'clang'.
1121 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1122 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001123 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001124 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1125 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001126 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001127 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001128 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001129
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001130 if (!ErrMsg.empty()) {
1131 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001132 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001133 I != E; ++I) {
1134 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001135 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001136 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001137 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001138
Daniel Dunbar32141c82010-02-23 20:23:45 +00001139 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001140 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001141
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001142 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001143 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001144 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001145 RemappedFiles.size(),
1146 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001147 if (ATU) {
1148 LoadSerializedDiagnostics(DiagnosticsFile,
1149 num_unsaved_files, unsaved_files,
1150 ATU->getFileManager(),
1151 ATU->getSourceManager(),
1152 ATU->getDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001153 } else if (CXXIdx->getDisplayDiagnostics()) {
1154 // We failed to load the ASTUnit, but we can still deserialize the
1155 // diagnostics and emit them.
1156 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001157 Diagnostic Diag;
1158 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001159 // FIXME: Faked LangOpts!
1160 LangOptions LangOpts;
1161 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1162 LoadSerializedDiagnostics(DiagnosticsFile,
1163 num_unsaved_files, unsaved_files,
1164 FileMgr, SourceMgr, Diags);
1165 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1166 DEnd = Diags.end();
1167 D != DEnd; ++D) {
1168 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001169 CXString Msg = clang_formatDiagnostic(&Diag,
1170 clang_defaultDiagnosticDisplayOptions());
1171 fprintf(stderr, "%s\n", clang_getCString(Msg));
1172 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001173 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001174
1175#ifdef LLVM_ON_WIN32
1176 // On Windows, force a flush, since there may be multiple copies of
1177 // stderr and stdout in the file system, all with different buffers
1178 // but writing to the same device.
1179 fflush(stderr);
1180#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001181 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001182
Douglas Gregor313e26c2010-02-18 23:35:40 +00001183 if (ATU) {
1184 // Make the translation unit responsible for destroying all temporary files.
1185 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1186 ATU->addTemporaryFile(TemporaryFiles[i]);
1187 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1188 } else {
1189 // Destroy all of the temporary files now; they can't be referenced any
1190 // longer.
1191 llvm::sys::Path(astTmpFile).eraseFromDisk();
1192 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1193 TemporaryFiles[i].eraseFromDisk();
1194 }
1195
Steve Naroffe19944c2009-10-15 22:23:48 +00001196 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001197}
1198
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001199void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001200 if (CTUnit)
1201 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001202}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001203
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001204CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001205 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001206 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001207
Steve Naroff77accc12009-09-03 18:19:54 +00001208 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001209 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001210}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001211
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001212CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001213 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001214 return Result;
1215}
1216
Ted Kremenekfb480492010-01-13 21:46:36 +00001217} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001218
Ted Kremenekfb480492010-01-13 21:46:36 +00001219//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001220// CXSourceLocation and CXSourceRange Operations.
1221//===----------------------------------------------------------------------===//
1222
Douglas Gregorb9790342010-01-22 21:44:22 +00001223extern "C" {
1224CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001225 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001226 return Result;
1227}
1228
1229unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001230 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1231 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1232 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001233}
1234
1235CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1236 CXFile file,
1237 unsigned line,
1238 unsigned column) {
1239 if (!tu)
1240 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001241
Douglas Gregorb9790342010-01-22 21:44:22 +00001242 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1243 SourceLocation SLoc
1244 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001245 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001246 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001247
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001248 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001249}
1250
Douglas Gregor5352ac02010-01-28 00:27:43 +00001251CXSourceRange clang_getNullRange() {
1252 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1253 return Result;
1254}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001255
Douglas Gregor5352ac02010-01-28 00:27:43 +00001256CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1257 if (begin.ptr_data[0] != end.ptr_data[0] ||
1258 begin.ptr_data[1] != end.ptr_data[1])
1259 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001260
1261 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001262 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001263 return Result;
1264}
1265
Douglas Gregor46766dc2010-01-26 19:19:08 +00001266void clang_getInstantiationLocation(CXSourceLocation location,
1267 CXFile *file,
1268 unsigned *line,
1269 unsigned *column,
1270 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001271 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1272
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001273 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001274 if (file)
1275 *file = 0;
1276 if (line)
1277 *line = 0;
1278 if (column)
1279 *column = 0;
1280 if (offset)
1281 *offset = 0;
1282 return;
1283 }
1284
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001285 const SourceManager &SM =
1286 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001287 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001288
1289 if (file)
1290 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1291 if (line)
1292 *line = SM.getInstantiationLineNumber(InstLoc);
1293 if (column)
1294 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001295 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001296 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001297}
1298
Douglas Gregor1db19de2010-01-19 21:36:55 +00001299CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001300 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001301 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001302 return Result;
1303}
1304
1305CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001306 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001307 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001308 return Result;
1309}
1310
Douglas Gregorb9790342010-01-22 21:44:22 +00001311} // end: extern "C"
1312
Douglas Gregor1db19de2010-01-19 21:36:55 +00001313//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001314// CXFile Operations.
1315//===----------------------------------------------------------------------===//
1316
1317extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001318CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001319 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001320 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001321
Steve Naroff88145032009-10-27 14:35:18 +00001322 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001323 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001324}
1325
1326time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001327 if (!SFile)
1328 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001329
Steve Naroff88145032009-10-27 14:35:18 +00001330 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1331 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001332}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001333
Douglas Gregorb9790342010-01-22 21:44:22 +00001334CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1335 if (!tu)
1336 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001337
Douglas Gregorb9790342010-01-22 21:44:22 +00001338 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001339
Douglas Gregorb9790342010-01-22 21:44:22 +00001340 FileManager &FMgr = CXXUnit->getFileManager();
1341 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1342 return const_cast<FileEntry *>(File);
1343}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001344
Ted Kremenekfb480492010-01-13 21:46:36 +00001345} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001346
Ted Kremenekfb480492010-01-13 21:46:36 +00001347//===----------------------------------------------------------------------===//
1348// CXCursor Operations.
1349//===----------------------------------------------------------------------===//
1350
Ted Kremenekfb480492010-01-13 21:46:36 +00001351static Decl *getDeclFromExpr(Stmt *E) {
1352 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1353 return RefExpr->getDecl();
1354 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1355 return ME->getMemberDecl();
1356 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1357 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001358
Ted Kremenekfb480492010-01-13 21:46:36 +00001359 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1360 return getDeclFromExpr(CE->getCallee());
1361 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1362 return getDeclFromExpr(CE->getSubExpr());
1363 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1364 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001365
Ted Kremenekfb480492010-01-13 21:46:36 +00001366 return 0;
1367}
1368
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001369static SourceLocation getLocationFromExpr(Expr *E) {
1370 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1371 return /*FIXME:*/Msg->getLeftLoc();
1372 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1373 return DRE->getLocation();
1374 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1375 return Member->getMemberLoc();
1376 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1377 return Ivar->getLocation();
1378 return E->getLocStart();
1379}
1380
Ted Kremenekfb480492010-01-13 21:46:36 +00001381extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001382
1383unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001384 CXCursorVisitor visitor,
1385 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001386 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001387
1388 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001389
Douglas Gregorb1373d02010-01-20 20:59:29 +00001390 // Set the PCHLevel to filter out unwanted decls if requested.
1391 if (CXXUnit->getOnlyLocalDecls()) {
1392 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001393
Douglas Gregorb1373d02010-01-20 20:59:29 +00001394 // If the main input was an AST, bump the level.
1395 if (CXXUnit->isMainFileAST())
1396 ++PCHLevel;
1397 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001398
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001399 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001400 return CursorVis.VisitChildren(parent);
1401}
1402
Douglas Gregor78205d42010-01-20 21:45:58 +00001403static CXString getDeclSpelling(Decl *D) {
1404 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1405 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001406 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001407
Douglas Gregor78205d42010-01-20 21:45:58 +00001408 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001409 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001410
Douglas Gregor78205d42010-01-20 21:45:58 +00001411 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1412 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1413 // and returns different names. NamedDecl returns the class name and
1414 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001415 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001416
Douglas Gregor78205d42010-01-20 21:45:58 +00001417 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001418 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001419
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001420 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001421}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001422
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001423CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001424 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001425 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001426
Steve Narofff334b4e2009-09-02 18:26:48 +00001427 if (clang_isReference(C.kind)) {
1428 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001429 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001430 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001431 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001432 }
1433 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001434 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001435 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001436 }
1437 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001438 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001439 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001440 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001441 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001442 case CXCursor_TypeRef: {
1443 TypeDecl *Type = getCursorTypeRef(C).first;
1444 assert(Type && "Missing type decl");
1445
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001446 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1447 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001448 }
1449
Daniel Dunbaracca7252009-11-30 20:42:49 +00001450 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001451 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001452 }
1453 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001454
1455 if (clang_isExpression(C.kind)) {
1456 Decl *D = getDeclFromExpr(getCursorExpr(C));
1457 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001458 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001459 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001460 }
1461
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001462 if (C.kind == CXCursor_MacroInstantiation)
1463 return createCXString(getCursorMacroInstantiation(C)->getName()
1464 ->getNameStart());
1465
Douglas Gregor572feb22010-03-18 18:04:21 +00001466 if (C.kind == CXCursor_MacroDefinition)
1467 return createCXString(getCursorMacroDefinition(C)->getName()
1468 ->getNameStart());
1469
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001470 if (clang_isDeclaration(C.kind))
1471 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001472
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001473 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001474}
1475
Ted Kremeneke68fff62010-02-17 00:41:32 +00001476CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001477 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001478 case CXCursor_FunctionDecl:
1479 return createCXString("FunctionDecl");
1480 case CXCursor_TypedefDecl:
1481 return createCXString("TypedefDecl");
1482 case CXCursor_EnumDecl:
1483 return createCXString("EnumDecl");
1484 case CXCursor_EnumConstantDecl:
1485 return createCXString("EnumConstantDecl");
1486 case CXCursor_StructDecl:
1487 return createCXString("StructDecl");
1488 case CXCursor_UnionDecl:
1489 return createCXString("UnionDecl");
1490 case CXCursor_ClassDecl:
1491 return createCXString("ClassDecl");
1492 case CXCursor_FieldDecl:
1493 return createCXString("FieldDecl");
1494 case CXCursor_VarDecl:
1495 return createCXString("VarDecl");
1496 case CXCursor_ParmDecl:
1497 return createCXString("ParmDecl");
1498 case CXCursor_ObjCInterfaceDecl:
1499 return createCXString("ObjCInterfaceDecl");
1500 case CXCursor_ObjCCategoryDecl:
1501 return createCXString("ObjCCategoryDecl");
1502 case CXCursor_ObjCProtocolDecl:
1503 return createCXString("ObjCProtocolDecl");
1504 case CXCursor_ObjCPropertyDecl:
1505 return createCXString("ObjCPropertyDecl");
1506 case CXCursor_ObjCIvarDecl:
1507 return createCXString("ObjCIvarDecl");
1508 case CXCursor_ObjCInstanceMethodDecl:
1509 return createCXString("ObjCInstanceMethodDecl");
1510 case CXCursor_ObjCClassMethodDecl:
1511 return createCXString("ObjCClassMethodDecl");
1512 case CXCursor_ObjCImplementationDecl:
1513 return createCXString("ObjCImplementationDecl");
1514 case CXCursor_ObjCCategoryImplDecl:
1515 return createCXString("ObjCCategoryImplDecl");
1516 case CXCursor_UnexposedDecl:
1517 return createCXString("UnexposedDecl");
1518 case CXCursor_ObjCSuperClassRef:
1519 return createCXString("ObjCSuperClassRef");
1520 case CXCursor_ObjCProtocolRef:
1521 return createCXString("ObjCProtocolRef");
1522 case CXCursor_ObjCClassRef:
1523 return createCXString("ObjCClassRef");
1524 case CXCursor_TypeRef:
1525 return createCXString("TypeRef");
1526 case CXCursor_UnexposedExpr:
1527 return createCXString("UnexposedExpr");
1528 case CXCursor_DeclRefExpr:
1529 return createCXString("DeclRefExpr");
1530 case CXCursor_MemberRefExpr:
1531 return createCXString("MemberRefExpr");
1532 case CXCursor_CallExpr:
1533 return createCXString("CallExpr");
1534 case CXCursor_ObjCMessageExpr:
1535 return createCXString("ObjCMessageExpr");
1536 case CXCursor_UnexposedStmt:
1537 return createCXString("UnexposedStmt");
1538 case CXCursor_InvalidFile:
1539 return createCXString("InvalidFile");
1540 case CXCursor_NoDeclFound:
1541 return createCXString("NoDeclFound");
1542 case CXCursor_NotImplemented:
1543 return createCXString("NotImplemented");
1544 case CXCursor_TranslationUnit:
1545 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001546 case CXCursor_UnexposedAttr:
1547 return createCXString("UnexposedAttr");
1548 case CXCursor_IBActionAttr:
1549 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001550 case CXCursor_IBOutletAttr:
1551 return createCXString("attribute(iboutlet)");
1552 case CXCursor_PreprocessingDirective:
1553 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001554 case CXCursor_MacroDefinition:
1555 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001556 case CXCursor_MacroInstantiation:
1557 return createCXString("macro instantiation");
Steve Naroff89922f82009-08-31 00:59:03 +00001558 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001559
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001560 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001561 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001562}
Steve Naroff89922f82009-08-31 00:59:03 +00001563
Ted Kremeneke68fff62010-02-17 00:41:32 +00001564enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1565 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001566 CXClientData client_data) {
1567 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1568 *BestCursor = cursor;
1569 return CXChildVisit_Recurse;
1570}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001571
Douglas Gregorb9790342010-01-22 21:44:22 +00001572CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1573 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001574 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001575
Douglas Gregorb9790342010-01-22 21:44:22 +00001576 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1577
Douglas Gregorbdf60622010-03-05 21:16:25 +00001578 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1579
Ted Kremeneka297de22010-01-25 22:34:44 +00001580 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001581 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1582 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001583 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001584
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001585 // FIXME: Would be great to have a "hint" cursor, then walk from that
1586 // hint cursor upward until we find a cursor whose source range encloses
1587 // the region of interest, rather than starting from the translation unit.
1588 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001589 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001590 Decl::MaxPCHLevel, RegionOfInterest);
1591 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001592 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001593 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001594}
1595
Ted Kremenek73885552009-11-17 19:28:59 +00001596CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001597 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001598}
1599
1600unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001601 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001602}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001603
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001604unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001605 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1606}
1607
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001608unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001609 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1610}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001611
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001612unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001613 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1614}
1615
Douglas Gregor97b98722010-01-19 23:20:36 +00001616unsigned clang_isExpression(enum CXCursorKind K) {
1617 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1618}
1619
1620unsigned clang_isStatement(enum CXCursorKind K) {
1621 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1622}
1623
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001624unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1625 return K == CXCursor_TranslationUnit;
1626}
1627
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001628unsigned clang_isPreprocessing(enum CXCursorKind K) {
1629 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1630}
1631
Ted Kremenekad6eff62010-03-08 21:17:29 +00001632unsigned clang_isUnexposed(enum CXCursorKind K) {
1633 switch (K) {
1634 case CXCursor_UnexposedDecl:
1635 case CXCursor_UnexposedExpr:
1636 case CXCursor_UnexposedStmt:
1637 case CXCursor_UnexposedAttr:
1638 return true;
1639 default:
1640 return false;
1641 }
1642}
1643
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001644CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001645 return C.kind;
1646}
1647
Douglas Gregor98258af2010-01-18 22:46:11 +00001648CXSourceLocation clang_getCursorLocation(CXCursor C) {
1649 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001650 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001651 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001652 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1653 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001654 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001655 }
1656
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001657 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001658 std::pair<ObjCProtocolDecl *, SourceLocation> P
1659 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001660 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001661 }
1662
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001663 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001664 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1665 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001666 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001667 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001668
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001669 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001670 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001671 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001672 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001673
Douglas Gregorf46034a2010-01-18 23:41:10 +00001674 default:
1675 // FIXME: Need a way to enumerate all non-reference cases.
1676 llvm_unreachable("Missed a reference kind");
1677 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001678 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001679
1680 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001681 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001682 getLocationFromExpr(getCursorExpr(C)));
1683
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001684 if (C.kind == CXCursor_PreprocessingDirective) {
1685 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1686 return cxloc::translateSourceLocation(getCursorContext(C), L);
1687 }
Douglas Gregor48072312010-03-18 15:23:44 +00001688
1689 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001690 SourceLocation L
1691 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001692 return cxloc::translateSourceLocation(getCursorContext(C), L);
1693 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001694
1695 if (C.kind == CXCursor_MacroDefinition) {
1696 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1697 return cxloc::translateSourceLocation(getCursorContext(C), L);
1698 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001699
Douglas Gregor5352ac02010-01-28 00:27:43 +00001700 if (!getCursorDecl(C))
1701 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001702
Douglas Gregorf46034a2010-01-18 23:41:10 +00001703 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001704 SourceLocation Loc = D->getLocation();
1705 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1706 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001707 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001708}
Douglas Gregora7bde202010-01-19 00:34:46 +00001709
1710CXSourceRange clang_getCursorExtent(CXCursor C) {
1711 if (clang_isReference(C.kind)) {
1712 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001713 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001714 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1715 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001716 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001717 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001718
1719 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001720 std::pair<ObjCProtocolDecl *, SourceLocation> P
1721 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001722 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001723 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001724
1725 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001726 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1727 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001728
Ted Kremeneka297de22010-01-25 22:34:44 +00001729 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001730 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001731
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001732 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001733 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001734 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001735 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001736
Douglas Gregora7bde202010-01-19 00:34:46 +00001737 default:
1738 // FIXME: Need a way to enumerate all non-reference cases.
1739 llvm_unreachable("Missed a reference kind");
1740 }
1741 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001742
1743 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001744 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001745 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001746
1747 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001748 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001749 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001750
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001751 if (C.kind == CXCursor_PreprocessingDirective) {
1752 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1753 return cxloc::translateSourceRange(getCursorContext(C), R);
1754 }
Douglas Gregor48072312010-03-18 15:23:44 +00001755
1756 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001757 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001758 return cxloc::translateSourceRange(getCursorContext(C), R);
1759 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001760
1761 if (C.kind == CXCursor_MacroDefinition) {
1762 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1763 return cxloc::translateSourceRange(getCursorContext(C), R);
1764 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001765
Douglas Gregor5352ac02010-01-28 00:27:43 +00001766 if (!getCursorDecl(C))
1767 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001768
Douglas Gregora7bde202010-01-19 00:34:46 +00001769 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001770 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001771}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001772
1773CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001774 if (clang_isInvalid(C.kind))
1775 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001776
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001777 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001778 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001779 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001780
Douglas Gregor97b98722010-01-19 23:20:36 +00001781 if (clang_isExpression(C.kind)) {
1782 Decl *D = getDeclFromExpr(getCursorExpr(C));
1783 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001784 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001785 return clang_getNullCursor();
1786 }
1787
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001788 if (C.kind == CXCursor_MacroInstantiation) {
1789 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1790 return MakeMacroDefinitionCursor(Def, CXXUnit);
1791 }
1792
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001793 if (!clang_isReference(C.kind))
1794 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001795
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001796 switch (C.kind) {
1797 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001798 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001799
1800 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001801 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001802
1803 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001804 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001805
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001806 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001807 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001808
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001809 default:
1810 // We would prefer to enumerate all non-reference cursor kinds here.
1811 llvm_unreachable("Unhandled reference cursor kind");
1812 break;
1813 }
1814 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001815
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001816 return clang_getNullCursor();
1817}
1818
Douglas Gregorb6998662010-01-19 19:34:47 +00001819CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001820 if (clang_isInvalid(C.kind))
1821 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001822
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001823 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001824
Douglas Gregorb6998662010-01-19 19:34:47 +00001825 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001826 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001827 C = clang_getCursorReferenced(C);
1828 WasReference = true;
1829 }
1830
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001831 if (C.kind == CXCursor_MacroInstantiation)
1832 return clang_getCursorReferenced(C);
1833
Douglas Gregorb6998662010-01-19 19:34:47 +00001834 if (!clang_isDeclaration(C.kind))
1835 return clang_getNullCursor();
1836
1837 Decl *D = getCursorDecl(C);
1838 if (!D)
1839 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001840
Douglas Gregorb6998662010-01-19 19:34:47 +00001841 switch (D->getKind()) {
1842 // Declaration kinds that don't really separate the notions of
1843 // declaration and definition.
1844 case Decl::Namespace:
1845 case Decl::Typedef:
1846 case Decl::TemplateTypeParm:
1847 case Decl::EnumConstant:
1848 case Decl::Field:
1849 case Decl::ObjCIvar:
1850 case Decl::ObjCAtDefsField:
1851 case Decl::ImplicitParam:
1852 case Decl::ParmVar:
1853 case Decl::NonTypeTemplateParm:
1854 case Decl::TemplateTemplateParm:
1855 case Decl::ObjCCategoryImpl:
1856 case Decl::ObjCImplementation:
1857 case Decl::LinkageSpec:
1858 case Decl::ObjCPropertyImpl:
1859 case Decl::FileScopeAsm:
1860 case Decl::StaticAssert:
1861 case Decl::Block:
1862 return C;
1863
1864 // Declaration kinds that don't make any sense here, but are
1865 // nonetheless harmless.
1866 case Decl::TranslationUnit:
1867 case Decl::Template:
1868 case Decl::ObjCContainer:
1869 break;
1870
1871 // Declaration kinds for which the definition is not resolvable.
1872 case Decl::UnresolvedUsingTypename:
1873 case Decl::UnresolvedUsingValue:
1874 break;
1875
1876 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001877 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1878 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001879
1880 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001881 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001882
1883 case Decl::Enum:
1884 case Decl::Record:
1885 case Decl::CXXRecord:
1886 case Decl::ClassTemplateSpecialization:
1887 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001888 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001889 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001890 return clang_getNullCursor();
1891
1892 case Decl::Function:
1893 case Decl::CXXMethod:
1894 case Decl::CXXConstructor:
1895 case Decl::CXXDestructor:
1896 case Decl::CXXConversion: {
1897 const FunctionDecl *Def = 0;
1898 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001899 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001900 return clang_getNullCursor();
1901 }
1902
1903 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001904 // Ask the variable if it has a definition.
1905 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1906 return MakeCXCursor(Def, CXXUnit);
1907 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001908 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001909
Douglas Gregorb6998662010-01-19 19:34:47 +00001910 case Decl::FunctionTemplate: {
1911 const FunctionDecl *Def = 0;
1912 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001913 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001914 return clang_getNullCursor();
1915 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001916
Douglas Gregorb6998662010-01-19 19:34:47 +00001917 case Decl::ClassTemplate: {
1918 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001919 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001920 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001921 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001922 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001923 return clang_getNullCursor();
1924 }
1925
1926 case Decl::Using: {
1927 UsingDecl *Using = cast<UsingDecl>(D);
1928 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001929 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1930 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001931 S != SEnd; ++S) {
1932 if (Def != clang_getNullCursor()) {
1933 // FIXME: We have no way to return multiple results.
1934 return clang_getNullCursor();
1935 }
1936
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001937 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001938 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001939 }
1940
1941 return Def;
1942 }
1943
1944 case Decl::UsingShadow:
1945 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001946 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001947 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001948
1949 case Decl::ObjCMethod: {
1950 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1951 if (Method->isThisDeclarationADefinition())
1952 return C;
1953
1954 // Dig out the method definition in the associated
1955 // @implementation, if we have it.
1956 // FIXME: The ASTs should make finding the definition easier.
1957 if (ObjCInterfaceDecl *Class
1958 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1959 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1960 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1961 Method->isInstanceMethod()))
1962 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001963 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001964
1965 return clang_getNullCursor();
1966 }
1967
1968 case Decl::ObjCCategory:
1969 if (ObjCCategoryImplDecl *Impl
1970 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001971 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001972 return clang_getNullCursor();
1973
1974 case Decl::ObjCProtocol:
1975 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1976 return C;
1977 return clang_getNullCursor();
1978
1979 case Decl::ObjCInterface:
1980 // There are two notions of a "definition" for an Objective-C
1981 // class: the interface and its implementation. When we resolved a
1982 // reference to an Objective-C class, produce the @interface as
1983 // the definition; when we were provided with the interface,
1984 // produce the @implementation as the definition.
1985 if (WasReference) {
1986 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1987 return C;
1988 } else if (ObjCImplementationDecl *Impl
1989 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001990 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001991 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001992
Douglas Gregorb6998662010-01-19 19:34:47 +00001993 case Decl::ObjCProperty:
1994 // FIXME: We don't really know where to find the
1995 // ObjCPropertyImplDecls that implement this property.
1996 return clang_getNullCursor();
1997
1998 case Decl::ObjCCompatibleAlias:
1999 if (ObjCInterfaceDecl *Class
2000 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2001 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002002 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002003
Douglas Gregorb6998662010-01-19 19:34:47 +00002004 return clang_getNullCursor();
2005
2006 case Decl::ObjCForwardProtocol: {
2007 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2008 if (Forward->protocol_size() == 1)
2009 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002010 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002011 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002012
2013 // FIXME: Cannot return multiple definitions.
2014 return clang_getNullCursor();
2015 }
2016
2017 case Decl::ObjCClass: {
2018 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2019 if (Class->size() == 1) {
2020 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2021 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002022 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002023 return clang_getNullCursor();
2024 }
2025
2026 // FIXME: Cannot return multiple definitions.
2027 return clang_getNullCursor();
2028 }
2029
2030 case Decl::Friend:
2031 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002032 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002033 return clang_getNullCursor();
2034
2035 case Decl::FriendTemplate:
2036 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002037 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002038 return clang_getNullCursor();
2039 }
2040
2041 return clang_getNullCursor();
2042}
2043
2044unsigned clang_isCursorDefinition(CXCursor C) {
2045 if (!clang_isDeclaration(C.kind))
2046 return 0;
2047
2048 return clang_getCursorDefinition(C) == C;
2049}
2050
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002051void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002052 const char **startBuf,
2053 const char **endBuf,
2054 unsigned *startLine,
2055 unsigned *startColumn,
2056 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002057 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002058 assert(getCursorDecl(C) && "CXCursor has null decl");
2059 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002060 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2061 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002062
Steve Naroff4ade6d62009-09-23 17:52:52 +00002063 SourceManager &SM = FD->getASTContext().getSourceManager();
2064 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2065 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2066 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2067 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2068 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2069 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2070}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002071
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002072void clang_enableStackTraces(void) {
2073 llvm::sys::PrintStackTraceOnErrorSignal();
2074}
2075
Ted Kremenekfb480492010-01-13 21:46:36 +00002076} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002077
Ted Kremenekfb480492010-01-13 21:46:36 +00002078//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002079// Token-based Operations.
2080//===----------------------------------------------------------------------===//
2081
2082/* CXToken layout:
2083 * int_data[0]: a CXTokenKind
2084 * int_data[1]: starting token location
2085 * int_data[2]: token length
2086 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002087 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002088 * otherwise unused.
2089 */
2090extern "C" {
2091
2092CXTokenKind clang_getTokenKind(CXToken CXTok) {
2093 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2094}
2095
2096CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2097 switch (clang_getTokenKind(CXTok)) {
2098 case CXToken_Identifier:
2099 case CXToken_Keyword:
2100 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002101 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2102 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002103
2104 case CXToken_Literal: {
2105 // We have stashed the starting pointer in the ptr_data field. Use it.
2106 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002107 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002108 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002109
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002110 case CXToken_Punctuation:
2111 case CXToken_Comment:
2112 break;
2113 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002114
2115 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002116 // deconstructing the source location.
2117 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2118 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002119 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002120
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002121 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2122 std::pair<FileID, unsigned> LocInfo
2123 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002124 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002125 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002126 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2127 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002128 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002129
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002130 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002131}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002132
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002133CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2134 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2135 if (!CXXUnit)
2136 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002137
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002138 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2139 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2140}
2141
2142CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2143 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002144 if (!CXXUnit)
2145 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002146
2147 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002148 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2149}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002150
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002151void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2152 CXToken **Tokens, unsigned *NumTokens) {
2153 if (Tokens)
2154 *Tokens = 0;
2155 if (NumTokens)
2156 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002157
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002158 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2159 if (!CXXUnit || !Tokens || !NumTokens)
2160 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002161
Douglas Gregorbdf60622010-03-05 21:16:25 +00002162 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2163
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002164 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002165 if (R.isInvalid())
2166 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002167
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002168 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2169 std::pair<FileID, unsigned> BeginLocInfo
2170 = SourceMgr.getDecomposedLoc(R.getBegin());
2171 std::pair<FileID, unsigned> EndLocInfo
2172 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002173
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002174 // Cannot tokenize across files.
2175 if (BeginLocInfo.first != EndLocInfo.first)
2176 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002177
2178 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002179 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002180 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002181 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002182 if (Invalid)
2183 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002184
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002185 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2186 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002187 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002188 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002189
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002190 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002191 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002192 llvm::SmallVector<CXToken, 32> CXTokens;
2193 Token Tok;
2194 do {
2195 // Lex the next token
2196 Lex.LexFromRawLexer(Tok);
2197 if (Tok.is(tok::eof))
2198 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002199
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002200 // Initialize the CXToken.
2201 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002202
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002203 // - Common fields
2204 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2205 CXTok.int_data[2] = Tok.getLength();
2206 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002207
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002208 // - Kind-specific fields
2209 if (Tok.isLiteral()) {
2210 CXTok.int_data[0] = CXToken_Literal;
2211 CXTok.ptr_data = (void *)Tok.getLiteralData();
2212 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002213 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002214 std::pair<FileID, unsigned> LocInfo
2215 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002216 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002217 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002218 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2219 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002220 return;
2221
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002222 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002223 IdentifierInfo *II
2224 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2225 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2226 CXToken_Identifier
2227 : CXToken_Keyword;
2228 CXTok.ptr_data = II;
2229 } else if (Tok.is(tok::comment)) {
2230 CXTok.int_data[0] = CXToken_Comment;
2231 CXTok.ptr_data = 0;
2232 } else {
2233 CXTok.int_data[0] = CXToken_Punctuation;
2234 CXTok.ptr_data = 0;
2235 }
2236 CXTokens.push_back(CXTok);
2237 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002238
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002239 if (CXTokens.empty())
2240 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002241
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002242 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2243 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2244 *NumTokens = CXTokens.size();
2245}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002246
2247typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2248
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002249enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2250 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002251 CXClientData client_data) {
2252 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2253
2254 // We only annotate the locations of declarations, simple
2255 // references, and expressions which directly reference something.
2256 CXCursorKind Kind = clang_getCursorKind(cursor);
2257 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2258 // Okay: We can annotate the location of this declaration with the
2259 // declaration or reference
2260 } else if (clang_isExpression(cursor.kind)) {
2261 if (Kind != CXCursor_DeclRefExpr &&
2262 Kind != CXCursor_MemberRefExpr &&
2263 Kind != CXCursor_ObjCMessageExpr)
2264 return CXChildVisit_Recurse;
2265
2266 CXCursor Referenced = clang_getCursorReferenced(cursor);
2267 if (Referenced == cursor || Referenced == clang_getNullCursor())
2268 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002269
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002270 // Okay: we can annotate the location of this expression
Douglas Gregor0396f462010-03-19 05:22:59 +00002271 } else if (clang_isPreprocessing(cursor.kind)) {
2272 // We can always annotate a preprocessing directive/macro instantiation.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002273 } else {
2274 // Nothing to annotate
2275 return CXChildVisit_Recurse;
2276 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002277
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002278 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2279 (*Data)[Loc.int_data] = cursor;
2280 return CXChildVisit_Recurse;
2281}
2282
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002283void clang_annotateTokens(CXTranslationUnit TU,
2284 CXToken *Tokens, unsigned NumTokens,
2285 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002286 if (NumTokens == 0)
2287 return;
2288
2289 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002290 for (unsigned I = 0; I != NumTokens; ++I)
2291 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002292
2293 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2294 if (!CXXUnit || !Tokens)
2295 return;
2296
Douglas Gregorbdf60622010-03-05 21:16:25 +00002297 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2298
Douglas Gregor0396f462010-03-19 05:22:59 +00002299 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002300 SourceRange RegionOfInterest;
2301 RegionOfInterest.setBegin(
2302 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2303 SourceLocation End
Douglas Gregor0396f462010-03-19 05:22:59 +00002304 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2305 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002306 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor2507fa82010-03-19 00:18:31 +00002307
Douglas Gregor0396f462010-03-19 05:22:59 +00002308 // A mapping from the source locations found when re-lexing or traversing the
2309 // region of interest to the corresponding cursors.
2310 AnnotateTokensData Annotated;
2311
2312 // Relex the tokens within the source range to look for preprocessing
2313 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002314 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2315 std::pair<FileID, unsigned> BeginLocInfo
2316 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2317 std::pair<FileID, unsigned> EndLocInfo
2318 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2319
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002320 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002321 bool Invalid = false;
2322 if (BeginLocInfo.first == EndLocInfo.first &&
2323 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2324 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002325 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2326 CXXUnit->getASTContext().getLangOptions(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002327 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2328 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002329 Lex.SetCommentRetentionState(true);
2330
2331 // Lex tokens in raw mode until we hit the end of the range, to avoid
2332 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002333 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002334 Token Tok;
2335 Lex.LexFromRawLexer(Tok);
2336
2337 reprocess:
2338 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2339 // We have found a preprocessing directive. Gobble it up so that we
2340 // don't see it while preprocessing these tokens later, but keep track of
2341 // all of the token locations inside this preprocessing directive so that
2342 // we can annotate them appropriately.
2343 //
2344 // FIXME: Some simple tests here could identify macro definitions and
2345 // #undefs, to provide specific cursor kinds for those.
2346 std::vector<SourceLocation> Locations;
2347 do {
2348 Locations.push_back(Tok.getLocation());
2349 Lex.LexFromRawLexer(Tok);
2350 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2351
2352 using namespace cxcursor;
2353 CXCursor Cursor
2354 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2355 Locations.back()),
2356 CXXUnit);
2357 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2358 Annotated[Locations[I].getRawEncoding()] = Cursor;
2359 }
2360
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002361 if (Tok.isAtStartOfLine())
2362 goto reprocess;
2363
2364 continue;
2365 }
2366
Douglas Gregor48072312010-03-18 15:23:44 +00002367 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002368 break;
2369 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002370 }
Douglas Gregor0396f462010-03-19 05:22:59 +00002371
2372 // Annotate all of the source locations in the region of interest that map to
2373 // a specific cursor.
2374 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2375 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2376 Decl::MaxPCHLevel, RegionOfInterest);
2377 AnnotateVis.VisitChildren(Parent);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002378
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002379 for (unsigned I = 0; I != NumTokens; ++I) {
2380 // Determine whether we saw a cursor at this token's location.
2381 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2382 if (Pos == Annotated.end())
2383 continue;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002384
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002385 Cursors[I] = Pos->second;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002386 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002387}
2388
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002389void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002390 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002391 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002392}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002393
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002394} // end: extern "C"
2395
2396//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002397// Operations for querying linkage of a cursor.
2398//===----------------------------------------------------------------------===//
2399
2400extern "C" {
2401CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002402 if (!clang_isDeclaration(cursor.kind))
2403 return CXLinkage_Invalid;
2404
Ted Kremenek16b42592010-03-03 06:36:57 +00002405 Decl *D = cxcursor::getCursorDecl(cursor);
2406 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2407 switch (ND->getLinkage()) {
2408 case NoLinkage: return CXLinkage_NoLinkage;
2409 case InternalLinkage: return CXLinkage_Internal;
2410 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2411 case ExternalLinkage: return CXLinkage_External;
2412 };
2413
2414 return CXLinkage_Invalid;
2415}
2416} // end: extern "C"
2417
2418//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002419// CXString Operations.
2420//===----------------------------------------------------------------------===//
2421
2422extern "C" {
2423const char *clang_getCString(CXString string) {
2424 return string.Spelling;
2425}
2426
2427void clang_disposeString(CXString string) {
2428 if (string.MustFreeString && string.Spelling)
2429 free((void*)string.Spelling);
2430}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002431
Ted Kremenekfb480492010-01-13 21:46:36 +00002432} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002433
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002434namespace clang { namespace cxstring {
2435CXString createCXString(const char *String, bool DupString){
2436 CXString Str;
2437 if (DupString) {
2438 Str.Spelling = strdup(String);
2439 Str.MustFreeString = 1;
2440 } else {
2441 Str.Spelling = String;
2442 Str.MustFreeString = 0;
2443 }
2444 return Str;
2445}
2446
2447CXString createCXString(llvm::StringRef String, bool DupString) {
2448 CXString Result;
2449 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2450 char *Spelling = (char *)malloc(String.size() + 1);
2451 memmove(Spelling, String.data(), String.size());
2452 Spelling[String.size()] = 0;
2453 Result.Spelling = Spelling;
2454 Result.MustFreeString = 1;
2455 } else {
2456 Result.Spelling = String.data();
2457 Result.MustFreeString = 0;
2458 }
2459 return Result;
2460}
2461}}
2462
Ted Kremenek04bb7162010-01-22 22:44:15 +00002463//===----------------------------------------------------------------------===//
2464// Misc. utility functions.
2465//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002466
Ted Kremenek04bb7162010-01-22 22:44:15 +00002467extern "C" {
2468
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002469CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002470 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002471}
2472
2473} // end: extern "C"