blob: f20bb753747732d307ca4c9e2b8b6880b50e3d58 [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.
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000433 if (PreprocessingRecord *PPRec
434 = CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000435 // FIXME: Once we have the ability to deserialize a preprocessing record,
436 // do so.
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000437 for (PreprocessingRecord::iterator E = PPRec->begin(),EEnd = PPRec->end();
Douglas Gregor0396f462010-03-19 05:22:59 +0000438 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);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001017 Args.push_back("-Xclang");
1018 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001019 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001020
Ted Kremenek29b72842010-01-07 22:49:05 +00001021#ifdef USE_CRASHTRACER
1022 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001023#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001024
Daniel Dunbar94220972009-12-05 02:17:18 +00001025 llvm::OwningPtr<ASTUnit> Unit(
1026 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001028 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001029 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001030 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001031 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001032 /*CaptureDiagnostics=*/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
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001117 argv.push_back("-Xclang");
1118 argv.push_back("-detailed-preprocessing-record");
1119
Ted Kremenek139ba862009-10-22 00:03:57 +00001120 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001121 argv.push_back(NULL);
1122
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001123 // Invoke 'clang'.
1124 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1125 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001126 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001127 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1128 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001129 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001130 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001131 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001132
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001133 if (!ErrMsg.empty()) {
1134 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001135 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001136 I != E; ++I) {
1137 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001138 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001139 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001140 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001141
Daniel Dunbar32141c82010-02-23 20:23:45 +00001142 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001143 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001144
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001145 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001146 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001147 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001148 RemappedFiles.size(),
1149 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001150 if (ATU) {
1151 LoadSerializedDiagnostics(DiagnosticsFile,
1152 num_unsaved_files, unsaved_files,
1153 ATU->getFileManager(),
1154 ATU->getSourceManager(),
1155 ATU->getDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001156 } else if (CXXIdx->getDisplayDiagnostics()) {
1157 // We failed to load the ASTUnit, but we can still deserialize the
1158 // diagnostics and emit them.
1159 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001160 Diagnostic Diag;
1161 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001162 // FIXME: Faked LangOpts!
1163 LangOptions LangOpts;
1164 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1165 LoadSerializedDiagnostics(DiagnosticsFile,
1166 num_unsaved_files, unsaved_files,
1167 FileMgr, SourceMgr, Diags);
1168 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1169 DEnd = Diags.end();
1170 D != DEnd; ++D) {
1171 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001172 CXString Msg = clang_formatDiagnostic(&Diag,
1173 clang_defaultDiagnosticDisplayOptions());
1174 fprintf(stderr, "%s\n", clang_getCString(Msg));
1175 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001176 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001177
1178#ifdef LLVM_ON_WIN32
1179 // On Windows, force a flush, since there may be multiple copies of
1180 // stderr and stdout in the file system, all with different buffers
1181 // but writing to the same device.
1182 fflush(stderr);
1183#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001184 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001185
Douglas Gregor313e26c2010-02-18 23:35:40 +00001186 if (ATU) {
1187 // Make the translation unit responsible for destroying all temporary files.
1188 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1189 ATU->addTemporaryFile(TemporaryFiles[i]);
1190 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1191 } else {
1192 // Destroy all of the temporary files now; they can't be referenced any
1193 // longer.
1194 llvm::sys::Path(astTmpFile).eraseFromDisk();
1195 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1196 TemporaryFiles[i].eraseFromDisk();
1197 }
1198
Steve Naroffe19944c2009-10-15 22:23:48 +00001199 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001200}
1201
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001202void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001203 if (CTUnit)
1204 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001205}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001206
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001207CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001208 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001209 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001210
Steve Naroff77accc12009-09-03 18:19:54 +00001211 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001212 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001213}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001214
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001215CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001216 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001217 return Result;
1218}
1219
Ted Kremenekfb480492010-01-13 21:46:36 +00001220} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001221
Ted Kremenekfb480492010-01-13 21:46:36 +00001222//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001223// CXSourceLocation and CXSourceRange Operations.
1224//===----------------------------------------------------------------------===//
1225
Douglas Gregorb9790342010-01-22 21:44:22 +00001226extern "C" {
1227CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001228 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001229 return Result;
1230}
1231
1232unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001233 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1234 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1235 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001236}
1237
1238CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1239 CXFile file,
1240 unsigned line,
1241 unsigned column) {
1242 if (!tu)
1243 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001244
Douglas Gregorb9790342010-01-22 21:44:22 +00001245 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1246 SourceLocation SLoc
1247 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001248 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001249 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001250
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001251 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001252}
1253
Douglas Gregor5352ac02010-01-28 00:27:43 +00001254CXSourceRange clang_getNullRange() {
1255 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1256 return Result;
1257}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001258
Douglas Gregor5352ac02010-01-28 00:27:43 +00001259CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1260 if (begin.ptr_data[0] != end.ptr_data[0] ||
1261 begin.ptr_data[1] != end.ptr_data[1])
1262 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001263
1264 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001265 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001266 return Result;
1267}
1268
Douglas Gregor46766dc2010-01-26 19:19:08 +00001269void clang_getInstantiationLocation(CXSourceLocation location,
1270 CXFile *file,
1271 unsigned *line,
1272 unsigned *column,
1273 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001274 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1275
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001276 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001277 if (file)
1278 *file = 0;
1279 if (line)
1280 *line = 0;
1281 if (column)
1282 *column = 0;
1283 if (offset)
1284 *offset = 0;
1285 return;
1286 }
1287
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001288 const SourceManager &SM =
1289 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001290 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001291
1292 if (file)
1293 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1294 if (line)
1295 *line = SM.getInstantiationLineNumber(InstLoc);
1296 if (column)
1297 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001298 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001299 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001300}
1301
Douglas Gregor1db19de2010-01-19 21:36:55 +00001302CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001303 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001304 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001305 return Result;
1306}
1307
1308CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001309 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001310 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001311 return Result;
1312}
1313
Douglas Gregorb9790342010-01-22 21:44:22 +00001314} // end: extern "C"
1315
Douglas Gregor1db19de2010-01-19 21:36:55 +00001316//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001317// CXFile Operations.
1318//===----------------------------------------------------------------------===//
1319
1320extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001321CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001322 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001323 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001324
Steve Naroff88145032009-10-27 14:35:18 +00001325 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001326 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001327}
1328
1329time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001330 if (!SFile)
1331 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001332
Steve Naroff88145032009-10-27 14:35:18 +00001333 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1334 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001335}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001336
Douglas Gregorb9790342010-01-22 21:44:22 +00001337CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1338 if (!tu)
1339 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001340
Douglas Gregorb9790342010-01-22 21:44:22 +00001341 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001342
Douglas Gregorb9790342010-01-22 21:44:22 +00001343 FileManager &FMgr = CXXUnit->getFileManager();
1344 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1345 return const_cast<FileEntry *>(File);
1346}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001347
Ted Kremenekfb480492010-01-13 21:46:36 +00001348} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001349
Ted Kremenekfb480492010-01-13 21:46:36 +00001350//===----------------------------------------------------------------------===//
1351// CXCursor Operations.
1352//===----------------------------------------------------------------------===//
1353
Ted Kremenekfb480492010-01-13 21:46:36 +00001354static Decl *getDeclFromExpr(Stmt *E) {
1355 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1356 return RefExpr->getDecl();
1357 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1358 return ME->getMemberDecl();
1359 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1360 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001361
Ted Kremenekfb480492010-01-13 21:46:36 +00001362 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1363 return getDeclFromExpr(CE->getCallee());
1364 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1365 return getDeclFromExpr(CE->getSubExpr());
1366 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1367 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001368
Ted Kremenekfb480492010-01-13 21:46:36 +00001369 return 0;
1370}
1371
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001372static SourceLocation getLocationFromExpr(Expr *E) {
1373 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1374 return /*FIXME:*/Msg->getLeftLoc();
1375 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1376 return DRE->getLocation();
1377 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1378 return Member->getMemberLoc();
1379 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1380 return Ivar->getLocation();
1381 return E->getLocStart();
1382}
1383
Ted Kremenekfb480492010-01-13 21:46:36 +00001384extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001385
1386unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001387 CXCursorVisitor visitor,
1388 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001389 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001390
1391 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001392
Douglas Gregorb1373d02010-01-20 20:59:29 +00001393 // Set the PCHLevel to filter out unwanted decls if requested.
1394 if (CXXUnit->getOnlyLocalDecls()) {
1395 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001396
Douglas Gregorb1373d02010-01-20 20:59:29 +00001397 // If the main input was an AST, bump the level.
1398 if (CXXUnit->isMainFileAST())
1399 ++PCHLevel;
1400 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001401
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001402 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001403 return CursorVis.VisitChildren(parent);
1404}
1405
Douglas Gregor78205d42010-01-20 21:45:58 +00001406static CXString getDeclSpelling(Decl *D) {
1407 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1408 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001409 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001410
Douglas Gregor78205d42010-01-20 21:45:58 +00001411 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001412 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001413
Douglas Gregor78205d42010-01-20 21:45:58 +00001414 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1415 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1416 // and returns different names. NamedDecl returns the class name and
1417 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001418 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001419
Douglas Gregor78205d42010-01-20 21:45:58 +00001420 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001421 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001422
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001423 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001424}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001425
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001426CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001427 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001428 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001429
Steve Narofff334b4e2009-09-02 18:26:48 +00001430 if (clang_isReference(C.kind)) {
1431 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001432 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001433 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001434 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001435 }
1436 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001437 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001438 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001439 }
1440 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001441 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001442 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001443 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001444 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001445 case CXCursor_TypeRef: {
1446 TypeDecl *Type = getCursorTypeRef(C).first;
1447 assert(Type && "Missing type decl");
1448
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001449 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1450 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001451 }
1452
Daniel Dunbaracca7252009-11-30 20:42:49 +00001453 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001454 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001455 }
1456 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001457
1458 if (clang_isExpression(C.kind)) {
1459 Decl *D = getDeclFromExpr(getCursorExpr(C));
1460 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001461 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001462 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001463 }
1464
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001465 if (C.kind == CXCursor_MacroInstantiation)
1466 return createCXString(getCursorMacroInstantiation(C)->getName()
1467 ->getNameStart());
1468
Douglas Gregor572feb22010-03-18 18:04:21 +00001469 if (C.kind == CXCursor_MacroDefinition)
1470 return createCXString(getCursorMacroDefinition(C)->getName()
1471 ->getNameStart());
1472
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001473 if (clang_isDeclaration(C.kind))
1474 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001475
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001476 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001477}
1478
Ted Kremeneke68fff62010-02-17 00:41:32 +00001479CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001480 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001481 case CXCursor_FunctionDecl:
1482 return createCXString("FunctionDecl");
1483 case CXCursor_TypedefDecl:
1484 return createCXString("TypedefDecl");
1485 case CXCursor_EnumDecl:
1486 return createCXString("EnumDecl");
1487 case CXCursor_EnumConstantDecl:
1488 return createCXString("EnumConstantDecl");
1489 case CXCursor_StructDecl:
1490 return createCXString("StructDecl");
1491 case CXCursor_UnionDecl:
1492 return createCXString("UnionDecl");
1493 case CXCursor_ClassDecl:
1494 return createCXString("ClassDecl");
1495 case CXCursor_FieldDecl:
1496 return createCXString("FieldDecl");
1497 case CXCursor_VarDecl:
1498 return createCXString("VarDecl");
1499 case CXCursor_ParmDecl:
1500 return createCXString("ParmDecl");
1501 case CXCursor_ObjCInterfaceDecl:
1502 return createCXString("ObjCInterfaceDecl");
1503 case CXCursor_ObjCCategoryDecl:
1504 return createCXString("ObjCCategoryDecl");
1505 case CXCursor_ObjCProtocolDecl:
1506 return createCXString("ObjCProtocolDecl");
1507 case CXCursor_ObjCPropertyDecl:
1508 return createCXString("ObjCPropertyDecl");
1509 case CXCursor_ObjCIvarDecl:
1510 return createCXString("ObjCIvarDecl");
1511 case CXCursor_ObjCInstanceMethodDecl:
1512 return createCXString("ObjCInstanceMethodDecl");
1513 case CXCursor_ObjCClassMethodDecl:
1514 return createCXString("ObjCClassMethodDecl");
1515 case CXCursor_ObjCImplementationDecl:
1516 return createCXString("ObjCImplementationDecl");
1517 case CXCursor_ObjCCategoryImplDecl:
1518 return createCXString("ObjCCategoryImplDecl");
1519 case CXCursor_UnexposedDecl:
1520 return createCXString("UnexposedDecl");
1521 case CXCursor_ObjCSuperClassRef:
1522 return createCXString("ObjCSuperClassRef");
1523 case CXCursor_ObjCProtocolRef:
1524 return createCXString("ObjCProtocolRef");
1525 case CXCursor_ObjCClassRef:
1526 return createCXString("ObjCClassRef");
1527 case CXCursor_TypeRef:
1528 return createCXString("TypeRef");
1529 case CXCursor_UnexposedExpr:
1530 return createCXString("UnexposedExpr");
1531 case CXCursor_DeclRefExpr:
1532 return createCXString("DeclRefExpr");
1533 case CXCursor_MemberRefExpr:
1534 return createCXString("MemberRefExpr");
1535 case CXCursor_CallExpr:
1536 return createCXString("CallExpr");
1537 case CXCursor_ObjCMessageExpr:
1538 return createCXString("ObjCMessageExpr");
1539 case CXCursor_UnexposedStmt:
1540 return createCXString("UnexposedStmt");
1541 case CXCursor_InvalidFile:
1542 return createCXString("InvalidFile");
1543 case CXCursor_NoDeclFound:
1544 return createCXString("NoDeclFound");
1545 case CXCursor_NotImplemented:
1546 return createCXString("NotImplemented");
1547 case CXCursor_TranslationUnit:
1548 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001549 case CXCursor_UnexposedAttr:
1550 return createCXString("UnexposedAttr");
1551 case CXCursor_IBActionAttr:
1552 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001553 case CXCursor_IBOutletAttr:
1554 return createCXString("attribute(iboutlet)");
1555 case CXCursor_PreprocessingDirective:
1556 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001557 case CXCursor_MacroDefinition:
1558 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001559 case CXCursor_MacroInstantiation:
1560 return createCXString("macro instantiation");
Steve Naroff89922f82009-08-31 00:59:03 +00001561 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001562
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001563 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001564 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001565}
Steve Naroff89922f82009-08-31 00:59:03 +00001566
Ted Kremeneke68fff62010-02-17 00:41:32 +00001567enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1568 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001569 CXClientData client_data) {
1570 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1571 *BestCursor = cursor;
1572 return CXChildVisit_Recurse;
1573}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001574
Douglas Gregorb9790342010-01-22 21:44:22 +00001575CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1576 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001577 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001578
Douglas Gregorb9790342010-01-22 21:44:22 +00001579 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1580
Douglas Gregorbdf60622010-03-05 21:16:25 +00001581 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1582
Ted Kremeneka297de22010-01-25 22:34:44 +00001583 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001584 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1585 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001586 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001587
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001588 // FIXME: Would be great to have a "hint" cursor, then walk from that
1589 // hint cursor upward until we find a cursor whose source range encloses
1590 // the region of interest, rather than starting from the translation unit.
1591 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001592 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001593 Decl::MaxPCHLevel, RegionOfInterest);
1594 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001595 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001596 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001597}
1598
Ted Kremenek73885552009-11-17 19:28:59 +00001599CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001600 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001601}
1602
1603unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001604 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001605}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001606
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001607unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001608 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1609}
1610
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001611unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001612 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1613}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001614
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001615unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001616 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1617}
1618
Douglas Gregor97b98722010-01-19 23:20:36 +00001619unsigned clang_isExpression(enum CXCursorKind K) {
1620 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1621}
1622
1623unsigned clang_isStatement(enum CXCursorKind K) {
1624 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1625}
1626
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001627unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1628 return K == CXCursor_TranslationUnit;
1629}
1630
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001631unsigned clang_isPreprocessing(enum CXCursorKind K) {
1632 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1633}
1634
Ted Kremenekad6eff62010-03-08 21:17:29 +00001635unsigned clang_isUnexposed(enum CXCursorKind K) {
1636 switch (K) {
1637 case CXCursor_UnexposedDecl:
1638 case CXCursor_UnexposedExpr:
1639 case CXCursor_UnexposedStmt:
1640 case CXCursor_UnexposedAttr:
1641 return true;
1642 default:
1643 return false;
1644 }
1645}
1646
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001647CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001648 return C.kind;
1649}
1650
Douglas Gregor98258af2010-01-18 22:46:11 +00001651CXSourceLocation clang_getCursorLocation(CXCursor C) {
1652 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001653 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001654 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001655 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1656 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001657 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001658 }
1659
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001660 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001661 std::pair<ObjCProtocolDecl *, SourceLocation> P
1662 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001663 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001664 }
1665
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001666 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001667 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1668 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001669 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001670 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001671
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001672 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001673 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001674 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001675 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001676
Douglas Gregorf46034a2010-01-18 23:41:10 +00001677 default:
1678 // FIXME: Need a way to enumerate all non-reference cases.
1679 llvm_unreachable("Missed a reference kind");
1680 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001681 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001682
1683 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001684 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001685 getLocationFromExpr(getCursorExpr(C)));
1686
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001687 if (C.kind == CXCursor_PreprocessingDirective) {
1688 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1689 return cxloc::translateSourceLocation(getCursorContext(C), L);
1690 }
Douglas Gregor48072312010-03-18 15:23:44 +00001691
1692 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001693 SourceLocation L
1694 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001695 return cxloc::translateSourceLocation(getCursorContext(C), L);
1696 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001697
1698 if (C.kind == CXCursor_MacroDefinition) {
1699 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1700 return cxloc::translateSourceLocation(getCursorContext(C), L);
1701 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001702
Douglas Gregor5352ac02010-01-28 00:27:43 +00001703 if (!getCursorDecl(C))
1704 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001705
Douglas Gregorf46034a2010-01-18 23:41:10 +00001706 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001707 SourceLocation Loc = D->getLocation();
1708 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1709 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001710 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001711}
Douglas Gregora7bde202010-01-19 00:34:46 +00001712
1713CXSourceRange clang_getCursorExtent(CXCursor C) {
1714 if (clang_isReference(C.kind)) {
1715 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001716 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001717 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1718 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001719 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001720 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001721
1722 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001723 std::pair<ObjCProtocolDecl *, SourceLocation> P
1724 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001725 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001726 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001727
1728 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001729 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1730 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001731
Ted Kremeneka297de22010-01-25 22:34:44 +00001732 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001733 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001734
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001735 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001736 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001737 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001738 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001739
Douglas Gregora7bde202010-01-19 00:34:46 +00001740 default:
1741 // FIXME: Need a way to enumerate all non-reference cases.
1742 llvm_unreachable("Missed a reference kind");
1743 }
1744 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001745
1746 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001747 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001748 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001749
1750 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001751 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001752 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001753
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001754 if (C.kind == CXCursor_PreprocessingDirective) {
1755 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1756 return cxloc::translateSourceRange(getCursorContext(C), R);
1757 }
Douglas Gregor48072312010-03-18 15:23:44 +00001758
1759 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001760 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001761 return cxloc::translateSourceRange(getCursorContext(C), R);
1762 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001763
1764 if (C.kind == CXCursor_MacroDefinition) {
1765 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1766 return cxloc::translateSourceRange(getCursorContext(C), R);
1767 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001768
Douglas Gregor5352ac02010-01-28 00:27:43 +00001769 if (!getCursorDecl(C))
1770 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001771
Douglas Gregora7bde202010-01-19 00:34:46 +00001772 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001773 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001774}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001775
1776CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001777 if (clang_isInvalid(C.kind))
1778 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001779
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001780 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001781 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001782 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001783
Douglas Gregor97b98722010-01-19 23:20:36 +00001784 if (clang_isExpression(C.kind)) {
1785 Decl *D = getDeclFromExpr(getCursorExpr(C));
1786 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001787 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001788 return clang_getNullCursor();
1789 }
1790
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001791 if (C.kind == CXCursor_MacroInstantiation) {
1792 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1793 return MakeMacroDefinitionCursor(Def, CXXUnit);
1794 }
1795
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001796 if (!clang_isReference(C.kind))
1797 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001798
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001799 switch (C.kind) {
1800 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001801 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001802
1803 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001804 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001805
1806 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001807 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001808
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001809 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001810 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001811
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001812 default:
1813 // We would prefer to enumerate all non-reference cursor kinds here.
1814 llvm_unreachable("Unhandled reference cursor kind");
1815 break;
1816 }
1817 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001818
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001819 return clang_getNullCursor();
1820}
1821
Douglas Gregorb6998662010-01-19 19:34:47 +00001822CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001823 if (clang_isInvalid(C.kind))
1824 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001825
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001826 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001827
Douglas Gregorb6998662010-01-19 19:34:47 +00001828 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001829 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001830 C = clang_getCursorReferenced(C);
1831 WasReference = true;
1832 }
1833
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001834 if (C.kind == CXCursor_MacroInstantiation)
1835 return clang_getCursorReferenced(C);
1836
Douglas Gregorb6998662010-01-19 19:34:47 +00001837 if (!clang_isDeclaration(C.kind))
1838 return clang_getNullCursor();
1839
1840 Decl *D = getCursorDecl(C);
1841 if (!D)
1842 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001843
Douglas Gregorb6998662010-01-19 19:34:47 +00001844 switch (D->getKind()) {
1845 // Declaration kinds that don't really separate the notions of
1846 // declaration and definition.
1847 case Decl::Namespace:
1848 case Decl::Typedef:
1849 case Decl::TemplateTypeParm:
1850 case Decl::EnumConstant:
1851 case Decl::Field:
1852 case Decl::ObjCIvar:
1853 case Decl::ObjCAtDefsField:
1854 case Decl::ImplicitParam:
1855 case Decl::ParmVar:
1856 case Decl::NonTypeTemplateParm:
1857 case Decl::TemplateTemplateParm:
1858 case Decl::ObjCCategoryImpl:
1859 case Decl::ObjCImplementation:
1860 case Decl::LinkageSpec:
1861 case Decl::ObjCPropertyImpl:
1862 case Decl::FileScopeAsm:
1863 case Decl::StaticAssert:
1864 case Decl::Block:
1865 return C;
1866
1867 // Declaration kinds that don't make any sense here, but are
1868 // nonetheless harmless.
1869 case Decl::TranslationUnit:
1870 case Decl::Template:
1871 case Decl::ObjCContainer:
1872 break;
1873
1874 // Declaration kinds for which the definition is not resolvable.
1875 case Decl::UnresolvedUsingTypename:
1876 case Decl::UnresolvedUsingValue:
1877 break;
1878
1879 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001880 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1881 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001882
1883 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001884 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001885
1886 case Decl::Enum:
1887 case Decl::Record:
1888 case Decl::CXXRecord:
1889 case Decl::ClassTemplateSpecialization:
1890 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001891 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001892 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001893 return clang_getNullCursor();
1894
1895 case Decl::Function:
1896 case Decl::CXXMethod:
1897 case Decl::CXXConstructor:
1898 case Decl::CXXDestructor:
1899 case Decl::CXXConversion: {
1900 const FunctionDecl *Def = 0;
1901 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001902 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001903 return clang_getNullCursor();
1904 }
1905
1906 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001907 // Ask the variable if it has a definition.
1908 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1909 return MakeCXCursor(Def, CXXUnit);
1910 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001911 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001912
Douglas Gregorb6998662010-01-19 19:34:47 +00001913 case Decl::FunctionTemplate: {
1914 const FunctionDecl *Def = 0;
1915 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001916 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001917 return clang_getNullCursor();
1918 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001919
Douglas Gregorb6998662010-01-19 19:34:47 +00001920 case Decl::ClassTemplate: {
1921 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001922 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001923 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001924 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001925 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001926 return clang_getNullCursor();
1927 }
1928
1929 case Decl::Using: {
1930 UsingDecl *Using = cast<UsingDecl>(D);
1931 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001932 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1933 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001934 S != SEnd; ++S) {
1935 if (Def != clang_getNullCursor()) {
1936 // FIXME: We have no way to return multiple results.
1937 return clang_getNullCursor();
1938 }
1939
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001940 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001941 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001942 }
1943
1944 return Def;
1945 }
1946
1947 case Decl::UsingShadow:
1948 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001949 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001950 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001951
1952 case Decl::ObjCMethod: {
1953 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1954 if (Method->isThisDeclarationADefinition())
1955 return C;
1956
1957 // Dig out the method definition in the associated
1958 // @implementation, if we have it.
1959 // FIXME: The ASTs should make finding the definition easier.
1960 if (ObjCInterfaceDecl *Class
1961 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1962 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1963 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1964 Method->isInstanceMethod()))
1965 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001966 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001967
1968 return clang_getNullCursor();
1969 }
1970
1971 case Decl::ObjCCategory:
1972 if (ObjCCategoryImplDecl *Impl
1973 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001974 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001975 return clang_getNullCursor();
1976
1977 case Decl::ObjCProtocol:
1978 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1979 return C;
1980 return clang_getNullCursor();
1981
1982 case Decl::ObjCInterface:
1983 // There are two notions of a "definition" for an Objective-C
1984 // class: the interface and its implementation. When we resolved a
1985 // reference to an Objective-C class, produce the @interface as
1986 // the definition; when we were provided with the interface,
1987 // produce the @implementation as the definition.
1988 if (WasReference) {
1989 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1990 return C;
1991 } else if (ObjCImplementationDecl *Impl
1992 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001993 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001994 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001995
Douglas Gregorb6998662010-01-19 19:34:47 +00001996 case Decl::ObjCProperty:
1997 // FIXME: We don't really know where to find the
1998 // ObjCPropertyImplDecls that implement this property.
1999 return clang_getNullCursor();
2000
2001 case Decl::ObjCCompatibleAlias:
2002 if (ObjCInterfaceDecl *Class
2003 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2004 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002005 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002006
Douglas Gregorb6998662010-01-19 19:34:47 +00002007 return clang_getNullCursor();
2008
2009 case Decl::ObjCForwardProtocol: {
2010 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2011 if (Forward->protocol_size() == 1)
2012 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002013 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002014 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002015
2016 // FIXME: Cannot return multiple definitions.
2017 return clang_getNullCursor();
2018 }
2019
2020 case Decl::ObjCClass: {
2021 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2022 if (Class->size() == 1) {
2023 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2024 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002025 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002026 return clang_getNullCursor();
2027 }
2028
2029 // FIXME: Cannot return multiple definitions.
2030 return clang_getNullCursor();
2031 }
2032
2033 case Decl::Friend:
2034 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002035 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002036 return clang_getNullCursor();
2037
2038 case Decl::FriendTemplate:
2039 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002040 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002041 return clang_getNullCursor();
2042 }
2043
2044 return clang_getNullCursor();
2045}
2046
2047unsigned clang_isCursorDefinition(CXCursor C) {
2048 if (!clang_isDeclaration(C.kind))
2049 return 0;
2050
2051 return clang_getCursorDefinition(C) == C;
2052}
2053
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002054void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002055 const char **startBuf,
2056 const char **endBuf,
2057 unsigned *startLine,
2058 unsigned *startColumn,
2059 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002060 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002061 assert(getCursorDecl(C) && "CXCursor has null decl");
2062 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002063 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2064 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002065
Steve Naroff4ade6d62009-09-23 17:52:52 +00002066 SourceManager &SM = FD->getASTContext().getSourceManager();
2067 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2068 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2069 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2070 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2071 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2072 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2073}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002074
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002075void clang_enableStackTraces(void) {
2076 llvm::sys::PrintStackTraceOnErrorSignal();
2077}
2078
Ted Kremenekfb480492010-01-13 21:46:36 +00002079} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002080
Ted Kremenekfb480492010-01-13 21:46:36 +00002081//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002082// Token-based Operations.
2083//===----------------------------------------------------------------------===//
2084
2085/* CXToken layout:
2086 * int_data[0]: a CXTokenKind
2087 * int_data[1]: starting token location
2088 * int_data[2]: token length
2089 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002090 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002091 * otherwise unused.
2092 */
2093extern "C" {
2094
2095CXTokenKind clang_getTokenKind(CXToken CXTok) {
2096 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2097}
2098
2099CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2100 switch (clang_getTokenKind(CXTok)) {
2101 case CXToken_Identifier:
2102 case CXToken_Keyword:
2103 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002104 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2105 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002106
2107 case CXToken_Literal: {
2108 // We have stashed the starting pointer in the ptr_data field. Use it.
2109 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002110 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002111 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002112
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002113 case CXToken_Punctuation:
2114 case CXToken_Comment:
2115 break;
2116 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002117
2118 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002119 // deconstructing the source location.
2120 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2121 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002122 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002123
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002124 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2125 std::pair<FileID, unsigned> LocInfo
2126 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002127 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002128 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002129 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2130 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002131 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002132
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002133 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002134}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002135
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002136CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2137 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2138 if (!CXXUnit)
2139 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002140
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002141 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2142 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2143}
2144
2145CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2146 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002147 if (!CXXUnit)
2148 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002149
2150 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002151 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2152}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002153
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002154void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2155 CXToken **Tokens, unsigned *NumTokens) {
2156 if (Tokens)
2157 *Tokens = 0;
2158 if (NumTokens)
2159 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002160
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002161 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2162 if (!CXXUnit || !Tokens || !NumTokens)
2163 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002164
Douglas Gregorbdf60622010-03-05 21:16:25 +00002165 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2166
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002167 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002168 if (R.isInvalid())
2169 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002170
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002171 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2172 std::pair<FileID, unsigned> BeginLocInfo
2173 = SourceMgr.getDecomposedLoc(R.getBegin());
2174 std::pair<FileID, unsigned> EndLocInfo
2175 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002176
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002177 // Cannot tokenize across files.
2178 if (BeginLocInfo.first != EndLocInfo.first)
2179 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002180
2181 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002182 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002183 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002184 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002185 if (Invalid)
2186 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002187
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002188 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2189 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002190 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002191 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002192
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002193 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002194 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002195 llvm::SmallVector<CXToken, 32> CXTokens;
2196 Token Tok;
2197 do {
2198 // Lex the next token
2199 Lex.LexFromRawLexer(Tok);
2200 if (Tok.is(tok::eof))
2201 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002202
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002203 // Initialize the CXToken.
2204 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002205
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002206 // - Common fields
2207 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2208 CXTok.int_data[2] = Tok.getLength();
2209 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002210
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002211 // - Kind-specific fields
2212 if (Tok.isLiteral()) {
2213 CXTok.int_data[0] = CXToken_Literal;
2214 CXTok.ptr_data = (void *)Tok.getLiteralData();
2215 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002216 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002217 std::pair<FileID, unsigned> LocInfo
2218 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002219 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002220 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002221 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2222 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002223 return;
2224
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002225 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002226 IdentifierInfo *II
2227 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2228 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2229 CXToken_Identifier
2230 : CXToken_Keyword;
2231 CXTok.ptr_data = II;
2232 } else if (Tok.is(tok::comment)) {
2233 CXTok.int_data[0] = CXToken_Comment;
2234 CXTok.ptr_data = 0;
2235 } else {
2236 CXTok.int_data[0] = CXToken_Punctuation;
2237 CXTok.ptr_data = 0;
2238 }
2239 CXTokens.push_back(CXTok);
2240 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002241
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002242 if (CXTokens.empty())
2243 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002244
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002245 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2246 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2247 *NumTokens = CXTokens.size();
2248}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002249
2250typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2251
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002252enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2253 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002254 CXClientData client_data) {
2255 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2256
2257 // We only annotate the locations of declarations, simple
2258 // references, and expressions which directly reference something.
2259 CXCursorKind Kind = clang_getCursorKind(cursor);
2260 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2261 // Okay: We can annotate the location of this declaration with the
2262 // declaration or reference
2263 } else if (clang_isExpression(cursor.kind)) {
2264 if (Kind != CXCursor_DeclRefExpr &&
2265 Kind != CXCursor_MemberRefExpr &&
2266 Kind != CXCursor_ObjCMessageExpr)
2267 return CXChildVisit_Recurse;
2268
2269 CXCursor Referenced = clang_getCursorReferenced(cursor);
2270 if (Referenced == cursor || Referenced == clang_getNullCursor())
2271 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002272
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002273 // Okay: we can annotate the location of this expression
Douglas Gregor0396f462010-03-19 05:22:59 +00002274 } else if (clang_isPreprocessing(cursor.kind)) {
2275 // We can always annotate a preprocessing directive/macro instantiation.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002276 } else {
2277 // Nothing to annotate
2278 return CXChildVisit_Recurse;
2279 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002280
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002281 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2282 (*Data)[Loc.int_data] = cursor;
2283 return CXChildVisit_Recurse;
2284}
2285
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002286void clang_annotateTokens(CXTranslationUnit TU,
2287 CXToken *Tokens, unsigned NumTokens,
2288 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002289 if (NumTokens == 0)
2290 return;
2291
2292 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002293 for (unsigned I = 0; I != NumTokens; ++I)
2294 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002295
2296 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2297 if (!CXXUnit || !Tokens)
2298 return;
2299
Douglas Gregorbdf60622010-03-05 21:16:25 +00002300 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2301
Douglas Gregor0396f462010-03-19 05:22:59 +00002302 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002303 SourceRange RegionOfInterest;
2304 RegionOfInterest.setBegin(
2305 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2306 SourceLocation End
Douglas Gregor0396f462010-03-19 05:22:59 +00002307 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2308 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002309 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor2507fa82010-03-19 00:18:31 +00002310
Douglas Gregor0396f462010-03-19 05:22:59 +00002311 // A mapping from the source locations found when re-lexing or traversing the
2312 // region of interest to the corresponding cursors.
2313 AnnotateTokensData Annotated;
2314
2315 // Relex the tokens within the source range to look for preprocessing
2316 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002317 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2318 std::pair<FileID, unsigned> BeginLocInfo
2319 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2320 std::pair<FileID, unsigned> EndLocInfo
2321 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2322
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002323 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002324 bool Invalid = false;
2325 if (BeginLocInfo.first == EndLocInfo.first &&
2326 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2327 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002328 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2329 CXXUnit->getASTContext().getLangOptions(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002330 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2331 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002332 Lex.SetCommentRetentionState(true);
2333
2334 // Lex tokens in raw mode until we hit the end of the range, to avoid
2335 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002336 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002337 Token Tok;
2338 Lex.LexFromRawLexer(Tok);
2339
2340 reprocess:
2341 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2342 // We have found a preprocessing directive. Gobble it up so that we
2343 // don't see it while preprocessing these tokens later, but keep track of
2344 // all of the token locations inside this preprocessing directive so that
2345 // we can annotate them appropriately.
2346 //
2347 // FIXME: Some simple tests here could identify macro definitions and
2348 // #undefs, to provide specific cursor kinds for those.
2349 std::vector<SourceLocation> Locations;
2350 do {
2351 Locations.push_back(Tok.getLocation());
2352 Lex.LexFromRawLexer(Tok);
2353 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2354
2355 using namespace cxcursor;
2356 CXCursor Cursor
2357 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2358 Locations.back()),
2359 CXXUnit);
2360 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2361 Annotated[Locations[I].getRawEncoding()] = Cursor;
2362 }
2363
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002364 if (Tok.isAtStartOfLine())
2365 goto reprocess;
2366
2367 continue;
2368 }
2369
Douglas Gregor48072312010-03-18 15:23:44 +00002370 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002371 break;
2372 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002373 }
Douglas Gregor0396f462010-03-19 05:22:59 +00002374
2375 // Annotate all of the source locations in the region of interest that map to
2376 // a specific cursor.
2377 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2378 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2379 Decl::MaxPCHLevel, RegionOfInterest);
2380 AnnotateVis.VisitChildren(Parent);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002381
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002382 for (unsigned I = 0; I != NumTokens; ++I) {
2383 // Determine whether we saw a cursor at this token's location.
2384 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2385 if (Pos == Annotated.end())
2386 continue;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002387
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002388 Cursors[I] = Pos->second;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002389 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002390}
2391
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002392void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002393 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002394 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002395}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002396
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002397} // end: extern "C"
2398
2399//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002400// Operations for querying linkage of a cursor.
2401//===----------------------------------------------------------------------===//
2402
2403extern "C" {
2404CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002405 if (!clang_isDeclaration(cursor.kind))
2406 return CXLinkage_Invalid;
2407
Ted Kremenek16b42592010-03-03 06:36:57 +00002408 Decl *D = cxcursor::getCursorDecl(cursor);
2409 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2410 switch (ND->getLinkage()) {
2411 case NoLinkage: return CXLinkage_NoLinkage;
2412 case InternalLinkage: return CXLinkage_Internal;
2413 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2414 case ExternalLinkage: return CXLinkage_External;
2415 };
2416
2417 return CXLinkage_Invalid;
2418}
2419} // end: extern "C"
2420
2421//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002422// CXString Operations.
2423//===----------------------------------------------------------------------===//
2424
2425extern "C" {
2426const char *clang_getCString(CXString string) {
2427 return string.Spelling;
2428}
2429
2430void clang_disposeString(CXString string) {
2431 if (string.MustFreeString && string.Spelling)
2432 free((void*)string.Spelling);
2433}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002434
Ted Kremenekfb480492010-01-13 21:46:36 +00002435} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002436
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002437namespace clang { namespace cxstring {
2438CXString createCXString(const char *String, bool DupString){
2439 CXString Str;
2440 if (DupString) {
2441 Str.Spelling = strdup(String);
2442 Str.MustFreeString = 1;
2443 } else {
2444 Str.Spelling = String;
2445 Str.MustFreeString = 0;
2446 }
2447 return Str;
2448}
2449
2450CXString createCXString(llvm::StringRef String, bool DupString) {
2451 CXString Result;
2452 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2453 char *Spelling = (char *)malloc(String.size() + 1);
2454 memmove(Spelling, String.data(), String.size());
2455 Spelling[String.size()] = 0;
2456 Result.Spelling = Spelling;
2457 Result.MustFreeString = 1;
2458 } else {
2459 Result.Spelling = String.data();
2460 Result.MustFreeString = 0;
2461 }
2462 return Result;
2463}
2464}}
2465
Ted Kremenek04bb7162010-01-22 22:44:15 +00002466//===----------------------------------------------------------------------===//
2467// Misc. utility functions.
2468//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002469
Ted Kremenek04bb7162010-01-22 22:44:15 +00002470extern "C" {
2471
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002472CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002473 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002474}
2475
2476} // end: extern "C"