blob: f20595e35674d426eea56f522025357aef2d4c96 [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 Kremenekebfa3392010-03-19 20:39:03 +0000624 // 'ID' could be null when dealing with invalid code.
625 if (ObjCInterfaceDecl *ID = D->getClassInterface())
626 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
627 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000628
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000629 return VisitObjCImplDecl(D);
630}
631
632bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
633#if 0
634 // Issue callbacks for super class.
635 // FIXME: No source location information!
636 if (D->getSuperClass() &&
637 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000638 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000639 TU)))
640 return true;
641#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000642
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000643 return VisitObjCImplDecl(D);
644}
645
646bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
647 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
648 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
649 E = D->protocol_end();
650 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000651 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000652 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000653
654 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000655}
656
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000657bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
658 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
659 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
660 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000661
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000662 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000663}
664
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000665bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
666 ASTContext &Context = TU->getASTContext();
667
668 // Some builtin types (such as Objective-C's "id", "sel", and
669 // "Class") have associated declarations. Create cursors for those.
670 QualType VisitType;
671 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000672 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000673 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000674 case BuiltinType::Char_U:
675 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000676 case BuiltinType::Char16:
677 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000678 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000679 case BuiltinType::UInt:
680 case BuiltinType::ULong:
681 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000682 case BuiltinType::UInt128:
683 case BuiltinType::Char_S:
684 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000685 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000686 case BuiltinType::Short:
687 case BuiltinType::Int:
688 case BuiltinType::Long:
689 case BuiltinType::LongLong:
690 case BuiltinType::Int128:
691 case BuiltinType::Float:
692 case BuiltinType::Double:
693 case BuiltinType::LongDouble:
694 case BuiltinType::NullPtr:
695 case BuiltinType::Overload:
696 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000697 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000698
699 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000700 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000701
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000702 case BuiltinType::ObjCId:
703 VisitType = Context.getObjCIdType();
704 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000705
706 case BuiltinType::ObjCClass:
707 VisitType = Context.getObjCClassType();
708 break;
709
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000710 case BuiltinType::ObjCSel:
711 VisitType = Context.getObjCSelType();
712 break;
713 }
714
715 if (!VisitType.isNull()) {
716 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000717 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000718 TU));
719 }
720
721 return false;
722}
723
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000724bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
725 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
726}
727
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000728bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
729 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
730}
731
732bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
733 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
734}
735
736bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
737 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
738 return true;
739
740 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
741 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
742 TU)))
743 return true;
744 }
745
746 return false;
747}
748
749bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
750 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
751 return true;
752
753 if (TL.hasProtocolsAsWritten()) {
754 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000755 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000756 TL.getProtocolLoc(I),
757 TU)))
758 return true;
759 }
760 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000761
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000762 return false;
763}
764
765bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
766 return Visit(TL.getPointeeLoc());
767}
768
769bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
770 return Visit(TL.getPointeeLoc());
771}
772
773bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
774 return Visit(TL.getPointeeLoc());
775}
776
777bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000778 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000779}
780
781bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000782 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000783}
784
785bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
786 if (Visit(TL.getResultLoc()))
787 return true;
788
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000789 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
790 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
791 return true;
792
793 return false;
794}
795
796bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
797 if (Visit(TL.getElementLoc()))
798 return true;
799
800 if (Expr *Size = TL.getSizeExpr())
801 return Visit(MakeCXCursor(Size, StmtParent, TU));
802
803 return false;
804}
805
Douglas Gregor2332c112010-01-21 20:48:56 +0000806bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
807 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
808}
809
810bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
811 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
812 return Visit(TSInfo->getTypeLoc());
813
814 return false;
815}
816
Douglas Gregora59e3902010-01-21 23:27:09 +0000817bool CursorVisitor::VisitStmt(Stmt *S) {
818 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
819 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000820 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000821 return true;
822 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000823
Douglas Gregora59e3902010-01-21 23:27:09 +0000824 return false;
825}
826
827bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
828 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
829 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000830 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000831 return true;
832 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000833
Douglas Gregora59e3902010-01-21 23:27:09 +0000834 return false;
835}
836
Douglas Gregorf5bab412010-01-22 01:00:11 +0000837bool CursorVisitor::VisitIfStmt(IfStmt *S) {
838 if (VarDecl *Var = S->getConditionVariable()) {
839 if (Visit(MakeCXCursor(Var, TU)))
840 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000841 }
842
Douglas Gregor263b47b2010-01-25 16:12:32 +0000843 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
844 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000845 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
846 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000847 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
848 return true;
849
850 return false;
851}
852
853bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
854 if (VarDecl *Var = S->getConditionVariable()) {
855 if (Visit(MakeCXCursor(Var, TU)))
856 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000857 }
858
Douglas Gregor263b47b2010-01-25 16:12:32 +0000859 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
860 return true;
861 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
862 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000863
Douglas Gregor263b47b2010-01-25 16:12:32 +0000864 return false;
865}
866
867bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
868 if (VarDecl *Var = S->getConditionVariable()) {
869 if (Visit(MakeCXCursor(Var, TU)))
870 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000871 }
872
Douglas Gregor263b47b2010-01-25 16:12:32 +0000873 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
874 return true;
875 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000876 return true;
877
Douglas Gregor263b47b2010-01-25 16:12:32 +0000878 return false;
879}
880
881bool CursorVisitor::VisitForStmt(ForStmt *S) {
882 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
883 return true;
884 if (VarDecl *Var = S->getConditionVariable()) {
885 if (Visit(MakeCXCursor(Var, TU)))
886 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000887 }
888
Douglas Gregor263b47b2010-01-25 16:12:32 +0000889 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
890 return true;
891 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
892 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000893 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
894 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000895
Douglas Gregorf5bab412010-01-22 01:00:11 +0000896 return false;
897}
898
Douglas Gregor336fd812010-01-23 00:40:08 +0000899bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
900 if (E->isArgumentType()) {
901 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
902 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000903
Douglas Gregor336fd812010-01-23 00:40:08 +0000904 return false;
905 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000906
Douglas Gregor336fd812010-01-23 00:40:08 +0000907 return VisitExpr(E);
908}
909
910bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
911 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
912 if (Visit(TSInfo->getTypeLoc()))
913 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000914
Douglas Gregor336fd812010-01-23 00:40:08 +0000915 return VisitCastExpr(E);
916}
917
918bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
919 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
920 if (Visit(TSInfo->getTypeLoc()))
921 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000922
Douglas Gregor336fd812010-01-23 00:40:08 +0000923 return VisitExpr(E);
924}
925
Douglas Gregorc2350e52010-03-08 16:40:19 +0000926bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
927 ObjCMessageExpr::ClassInfo CI = E->getClassInfo();
928 if (CI.Decl && Visit(MakeCursorObjCClassRef(CI.Decl, CI.Loc, TU)))
929 return true;
930
931 return VisitExpr(E);
932}
933
Ted Kremenek09dfa372010-02-18 05:46:33 +0000934bool CursorVisitor::VisitAttributes(Decl *D) {
935 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
936 if (Visit(MakeCXCursor(A, D, TU)))
937 return true;
938
939 return false;
940}
941
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000942extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000943CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
944 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000945 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000946 if (excludeDeclarationsFromPCH)
947 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000948 if (displayDiagnostics)
949 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000950 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000951}
952
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000953void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000954 if (CIdx)
955 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000956}
957
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000958void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000959 if (CIdx) {
960 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
961 CXXIdx->setUseExternalASTGeneration(value);
962 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000963}
964
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000965CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +0000966 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000967 if (!CIdx)
968 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000969
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000970 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000971
Douglas Gregor5352ac02010-01-28 00:27:43 +0000972 // Configure the diagnostics.
973 DiagnosticOptions DiagOpts;
974 llvm::OwningPtr<Diagnostic> Diags;
975 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Douglas Gregor5352ac02010-01-28 00:27:43 +0000976 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +0000977 CXXIdx->getOnlyLocalDecls(),
978 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +0000979}
980
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000981CXTranslationUnit
982clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
983 const char *source_filename,
984 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000985 const char **command_line_args,
986 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +0000987 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000988 if (!CIdx)
989 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000990
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000991 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
992
Douglas Gregor5352ac02010-01-28 00:27:43 +0000993 // Configure the diagnostics.
994 DiagnosticOptions DiagOpts;
995 llvm::OwningPtr<Diagnostic> Diags;
996 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000997
Douglas Gregor4db64a42010-01-23 00:14:00 +0000998 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
999 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001000 const llvm::MemoryBuffer *Buffer
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +00001001 = llvm::MemoryBuffer::getMemBufferCopy(unsaved_files[I].Contents,
Douglas Gregor313e26c2010-02-18 23:35:40 +00001002 unsaved_files[I].Contents + unsaved_files[I].Length,
1003 unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001004 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1005 Buffer));
1006 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001007
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001008 if (!CXXIdx->getUseExternalASTGeneration()) {
1009 llvm::SmallVector<const char *, 16> Args;
1010
1011 // The 'source_filename' argument is optional. If the caller does not
1012 // specify it then it is assumed that the source file is specified
1013 // in the actual argument list.
1014 if (source_filename)
1015 Args.push_back(source_filename);
1016 Args.insert(Args.end(), command_line_args,
1017 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001018 Args.push_back("-Xclang");
1019 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001020 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001021
Ted Kremenek29b72842010-01-07 22:49:05 +00001022#ifdef USE_CRASHTRACER
1023 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001024#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001025
Daniel Dunbar94220972009-12-05 02:17:18 +00001026 llvm::OwningPtr<ASTUnit> Unit(
1027 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001028 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001029 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001030 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001031 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001032 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001033 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001034
Daniel Dunbar94220972009-12-05 02:17:18 +00001035 // FIXME: Until we have broader testing, just drop the entire AST if we
1036 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001037 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001038 // Make sure to check that 'Unit' is non-NULL.
1039 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001040 for (ASTUnit::diag_iterator D = Unit->diag_begin(),
1041 DEnd = Unit->diag_end();
1042 D != DEnd; ++D) {
1043 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001044 CXString Msg = clang_formatDiagnostic(&Diag,
1045 clang_defaultDiagnosticDisplayOptions());
1046 fprintf(stderr, "%s\n", clang_getCString(Msg));
1047 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001048 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001049#ifdef LLVM_ON_WIN32
1050 // On Windows, force a flush, since there may be multiple copies of
1051 // stderr and stdout in the file system, all with different buffers
1052 // but writing to the same device.
1053 fflush(stderr);
1054#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001055 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001056 return 0;
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001057 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001058
1059 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001060 }
1061
Ted Kremenek139ba862009-10-22 00:03:57 +00001062 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001063 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001064
Ted Kremenek139ba862009-10-22 00:03:57 +00001065 // First add the complete path to the 'clang' executable.
1066 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001067 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001068
Ted Kremenek139ba862009-10-22 00:03:57 +00001069 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001070 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001071
Ted Kremenek139ba862009-10-22 00:03:57 +00001072 // The 'source_filename' argument is optional. If the caller does not
1073 // specify it then it is assumed that the source file is specified
1074 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001075 if (source_filename)
1076 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001077
Steve Naroff37b5ac22009-10-15 20:50:09 +00001078 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001079 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001080 char astTmpFile[L_tmpnam];
1081 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001082
Douglas Gregor4db64a42010-01-23 00:14:00 +00001083 // Remap any unsaved files to temporary files.
1084 std::vector<llvm::sys::Path> TemporaryFiles;
1085 std::vector<std::string> RemapArgs;
1086 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1087 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001088
Douglas Gregor4db64a42010-01-23 00:14:00 +00001089 // The pointers into the elements of RemapArgs are stable because we
1090 // won't be adding anything to RemapArgs after this point.
1091 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1092 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001093
Ted Kremenek139ba862009-10-22 00:03:57 +00001094 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1095 for (int i = 0; i < num_command_line_args; ++i)
1096 if (const char *arg = command_line_args[i]) {
1097 if (strcmp(arg, "-o") == 0) {
1098 ++i; // Also skip the matching argument.
1099 continue;
1100 }
1101 if (strcmp(arg, "-emit-ast") == 0 ||
1102 strcmp(arg, "-c") == 0 ||
1103 strcmp(arg, "-fsyntax-only") == 0) {
1104 continue;
1105 }
1106
1107 // Keep the argument.
1108 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001109 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001110
Douglas Gregord93256e2010-01-28 06:00:51 +00001111 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001112 char tmpFileResults[L_tmpnam];
1113 char *tmpResultsFileName = tmpnam(tmpFileResults);
1114 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001115 TemporaryFiles.push_back(DiagnosticsFile);
1116 argv.push_back("-fdiagnostics-binary");
1117
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001118 argv.push_back("-Xclang");
1119 argv.push_back("-detailed-preprocessing-record");
1120
Ted Kremenek139ba862009-10-22 00:03:57 +00001121 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001122 argv.push_back(NULL);
1123
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001124 // Invoke 'clang'.
1125 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1126 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001127 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001128 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1129 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001130 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001131 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001132 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001133
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001134 if (!ErrMsg.empty()) {
1135 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001136 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001137 I != E; ++I) {
1138 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001139 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001140 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001141 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001142
Daniel Dunbar32141c82010-02-23 20:23:45 +00001143 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001144 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001145
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001146 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001147 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001148 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001149 RemappedFiles.size(),
1150 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001151 if (ATU) {
1152 LoadSerializedDiagnostics(DiagnosticsFile,
1153 num_unsaved_files, unsaved_files,
1154 ATU->getFileManager(),
1155 ATU->getSourceManager(),
1156 ATU->getDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001157 } else if (CXXIdx->getDisplayDiagnostics()) {
1158 // We failed to load the ASTUnit, but we can still deserialize the
1159 // diagnostics and emit them.
1160 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001161 Diagnostic Diag;
1162 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001163 // FIXME: Faked LangOpts!
1164 LangOptions LangOpts;
1165 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1166 LoadSerializedDiagnostics(DiagnosticsFile,
1167 num_unsaved_files, unsaved_files,
1168 FileMgr, SourceMgr, Diags);
1169 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1170 DEnd = Diags.end();
1171 D != DEnd; ++D) {
1172 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001173 CXString Msg = clang_formatDiagnostic(&Diag,
1174 clang_defaultDiagnosticDisplayOptions());
1175 fprintf(stderr, "%s\n", clang_getCString(Msg));
1176 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001177 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001178
1179#ifdef LLVM_ON_WIN32
1180 // On Windows, force a flush, since there may be multiple copies of
1181 // stderr and stdout in the file system, all with different buffers
1182 // but writing to the same device.
1183 fflush(stderr);
1184#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001185 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001186
Douglas Gregor313e26c2010-02-18 23:35:40 +00001187 if (ATU) {
1188 // Make the translation unit responsible for destroying all temporary files.
1189 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1190 ATU->addTemporaryFile(TemporaryFiles[i]);
1191 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1192 } else {
1193 // Destroy all of the temporary files now; they can't be referenced any
1194 // longer.
1195 llvm::sys::Path(astTmpFile).eraseFromDisk();
1196 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1197 TemporaryFiles[i].eraseFromDisk();
1198 }
1199
Steve Naroffe19944c2009-10-15 22:23:48 +00001200 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001201}
1202
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001203void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001204 if (CTUnit)
1205 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001206}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001207
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001208CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001209 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001210 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001211
Steve Naroff77accc12009-09-03 18:19:54 +00001212 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001213 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001214}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001215
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001216CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001217 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001218 return Result;
1219}
1220
Ted Kremenekfb480492010-01-13 21:46:36 +00001221} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001222
Ted Kremenekfb480492010-01-13 21:46:36 +00001223//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001224// CXSourceLocation and CXSourceRange Operations.
1225//===----------------------------------------------------------------------===//
1226
Douglas Gregorb9790342010-01-22 21:44:22 +00001227extern "C" {
1228CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001229 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001230 return Result;
1231}
1232
1233unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001234 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1235 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1236 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001237}
1238
1239CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1240 CXFile file,
1241 unsigned line,
1242 unsigned column) {
1243 if (!tu)
1244 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001245
Douglas Gregorb9790342010-01-22 21:44:22 +00001246 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1247 SourceLocation SLoc
1248 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001249 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001250 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001251
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001252 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001253}
1254
Douglas Gregor5352ac02010-01-28 00:27:43 +00001255CXSourceRange clang_getNullRange() {
1256 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1257 return Result;
1258}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001259
Douglas Gregor5352ac02010-01-28 00:27:43 +00001260CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1261 if (begin.ptr_data[0] != end.ptr_data[0] ||
1262 begin.ptr_data[1] != end.ptr_data[1])
1263 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001264
1265 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001266 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001267 return Result;
1268}
1269
Douglas Gregor46766dc2010-01-26 19:19:08 +00001270void clang_getInstantiationLocation(CXSourceLocation location,
1271 CXFile *file,
1272 unsigned *line,
1273 unsigned *column,
1274 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001275 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1276
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001277 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001278 if (file)
1279 *file = 0;
1280 if (line)
1281 *line = 0;
1282 if (column)
1283 *column = 0;
1284 if (offset)
1285 *offset = 0;
1286 return;
1287 }
1288
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001289 const SourceManager &SM =
1290 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001291 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001292
1293 if (file)
1294 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1295 if (line)
1296 *line = SM.getInstantiationLineNumber(InstLoc);
1297 if (column)
1298 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001299 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001300 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001301}
1302
Douglas Gregor1db19de2010-01-19 21:36:55 +00001303CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001304 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001305 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001306 return Result;
1307}
1308
1309CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001310 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001311 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001312 return Result;
1313}
1314
Douglas Gregorb9790342010-01-22 21:44:22 +00001315} // end: extern "C"
1316
Douglas Gregor1db19de2010-01-19 21:36:55 +00001317//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001318// CXFile Operations.
1319//===----------------------------------------------------------------------===//
1320
1321extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001322CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001323 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001324 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001325
Steve Naroff88145032009-10-27 14:35:18 +00001326 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001327 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001328}
1329
1330time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001331 if (!SFile)
1332 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001333
Steve Naroff88145032009-10-27 14:35:18 +00001334 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1335 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001336}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001337
Douglas Gregorb9790342010-01-22 21:44:22 +00001338CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1339 if (!tu)
1340 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001341
Douglas Gregorb9790342010-01-22 21:44:22 +00001342 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001343
Douglas Gregorb9790342010-01-22 21:44:22 +00001344 FileManager &FMgr = CXXUnit->getFileManager();
1345 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1346 return const_cast<FileEntry *>(File);
1347}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001348
Ted Kremenekfb480492010-01-13 21:46:36 +00001349} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001350
Ted Kremenekfb480492010-01-13 21:46:36 +00001351//===----------------------------------------------------------------------===//
1352// CXCursor Operations.
1353//===----------------------------------------------------------------------===//
1354
Ted Kremenekfb480492010-01-13 21:46:36 +00001355static Decl *getDeclFromExpr(Stmt *E) {
1356 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1357 return RefExpr->getDecl();
1358 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1359 return ME->getMemberDecl();
1360 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1361 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001362
Ted Kremenekfb480492010-01-13 21:46:36 +00001363 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1364 return getDeclFromExpr(CE->getCallee());
1365 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1366 return getDeclFromExpr(CE->getSubExpr());
1367 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1368 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001369
Ted Kremenekfb480492010-01-13 21:46:36 +00001370 return 0;
1371}
1372
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001373static SourceLocation getLocationFromExpr(Expr *E) {
1374 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1375 return /*FIXME:*/Msg->getLeftLoc();
1376 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1377 return DRE->getLocation();
1378 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1379 return Member->getMemberLoc();
1380 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1381 return Ivar->getLocation();
1382 return E->getLocStart();
1383}
1384
Ted Kremenekfb480492010-01-13 21:46:36 +00001385extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001386
1387unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001388 CXCursorVisitor visitor,
1389 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001390 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001391
1392 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001393
Douglas Gregorb1373d02010-01-20 20:59:29 +00001394 // Set the PCHLevel to filter out unwanted decls if requested.
1395 if (CXXUnit->getOnlyLocalDecls()) {
1396 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001397
Douglas Gregorb1373d02010-01-20 20:59:29 +00001398 // If the main input was an AST, bump the level.
1399 if (CXXUnit->isMainFileAST())
1400 ++PCHLevel;
1401 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001402
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001403 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001404 return CursorVis.VisitChildren(parent);
1405}
1406
Douglas Gregor78205d42010-01-20 21:45:58 +00001407static CXString getDeclSpelling(Decl *D) {
1408 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1409 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001410 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001411
Douglas Gregor78205d42010-01-20 21:45:58 +00001412 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001413 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001414
Douglas Gregor78205d42010-01-20 21:45:58 +00001415 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1416 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1417 // and returns different names. NamedDecl returns the class name and
1418 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001419 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001420
Douglas Gregor78205d42010-01-20 21:45:58 +00001421 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001422 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001423
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001424 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001425}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001426
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001427CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001428 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001429 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001430
Steve Narofff334b4e2009-09-02 18:26:48 +00001431 if (clang_isReference(C.kind)) {
1432 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001433 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001434 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001435 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001436 }
1437 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001438 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001439 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001440 }
1441 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001442 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001443 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001444 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001445 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001446 case CXCursor_TypeRef: {
1447 TypeDecl *Type = getCursorTypeRef(C).first;
1448 assert(Type && "Missing type decl");
1449
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001450 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1451 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001452 }
1453
Daniel Dunbaracca7252009-11-30 20:42:49 +00001454 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001455 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001456 }
1457 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001458
1459 if (clang_isExpression(C.kind)) {
1460 Decl *D = getDeclFromExpr(getCursorExpr(C));
1461 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001462 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001463 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001464 }
1465
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001466 if (C.kind == CXCursor_MacroInstantiation)
1467 return createCXString(getCursorMacroInstantiation(C)->getName()
1468 ->getNameStart());
1469
Douglas Gregor572feb22010-03-18 18:04:21 +00001470 if (C.kind == CXCursor_MacroDefinition)
1471 return createCXString(getCursorMacroDefinition(C)->getName()
1472 ->getNameStart());
1473
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001474 if (clang_isDeclaration(C.kind))
1475 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001476
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001477 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001478}
1479
Ted Kremeneke68fff62010-02-17 00:41:32 +00001480CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001481 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001482 case CXCursor_FunctionDecl:
1483 return createCXString("FunctionDecl");
1484 case CXCursor_TypedefDecl:
1485 return createCXString("TypedefDecl");
1486 case CXCursor_EnumDecl:
1487 return createCXString("EnumDecl");
1488 case CXCursor_EnumConstantDecl:
1489 return createCXString("EnumConstantDecl");
1490 case CXCursor_StructDecl:
1491 return createCXString("StructDecl");
1492 case CXCursor_UnionDecl:
1493 return createCXString("UnionDecl");
1494 case CXCursor_ClassDecl:
1495 return createCXString("ClassDecl");
1496 case CXCursor_FieldDecl:
1497 return createCXString("FieldDecl");
1498 case CXCursor_VarDecl:
1499 return createCXString("VarDecl");
1500 case CXCursor_ParmDecl:
1501 return createCXString("ParmDecl");
1502 case CXCursor_ObjCInterfaceDecl:
1503 return createCXString("ObjCInterfaceDecl");
1504 case CXCursor_ObjCCategoryDecl:
1505 return createCXString("ObjCCategoryDecl");
1506 case CXCursor_ObjCProtocolDecl:
1507 return createCXString("ObjCProtocolDecl");
1508 case CXCursor_ObjCPropertyDecl:
1509 return createCXString("ObjCPropertyDecl");
1510 case CXCursor_ObjCIvarDecl:
1511 return createCXString("ObjCIvarDecl");
1512 case CXCursor_ObjCInstanceMethodDecl:
1513 return createCXString("ObjCInstanceMethodDecl");
1514 case CXCursor_ObjCClassMethodDecl:
1515 return createCXString("ObjCClassMethodDecl");
1516 case CXCursor_ObjCImplementationDecl:
1517 return createCXString("ObjCImplementationDecl");
1518 case CXCursor_ObjCCategoryImplDecl:
1519 return createCXString("ObjCCategoryImplDecl");
1520 case CXCursor_UnexposedDecl:
1521 return createCXString("UnexposedDecl");
1522 case CXCursor_ObjCSuperClassRef:
1523 return createCXString("ObjCSuperClassRef");
1524 case CXCursor_ObjCProtocolRef:
1525 return createCXString("ObjCProtocolRef");
1526 case CXCursor_ObjCClassRef:
1527 return createCXString("ObjCClassRef");
1528 case CXCursor_TypeRef:
1529 return createCXString("TypeRef");
1530 case CXCursor_UnexposedExpr:
1531 return createCXString("UnexposedExpr");
1532 case CXCursor_DeclRefExpr:
1533 return createCXString("DeclRefExpr");
1534 case CXCursor_MemberRefExpr:
1535 return createCXString("MemberRefExpr");
1536 case CXCursor_CallExpr:
1537 return createCXString("CallExpr");
1538 case CXCursor_ObjCMessageExpr:
1539 return createCXString("ObjCMessageExpr");
1540 case CXCursor_UnexposedStmt:
1541 return createCXString("UnexposedStmt");
1542 case CXCursor_InvalidFile:
1543 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001544 case CXCursor_InvalidCode:
1545 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001546 case CXCursor_NoDeclFound:
1547 return createCXString("NoDeclFound");
1548 case CXCursor_NotImplemented:
1549 return createCXString("NotImplemented");
1550 case CXCursor_TranslationUnit:
1551 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001552 case CXCursor_UnexposedAttr:
1553 return createCXString("UnexposedAttr");
1554 case CXCursor_IBActionAttr:
1555 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001556 case CXCursor_IBOutletAttr:
1557 return createCXString("attribute(iboutlet)");
1558 case CXCursor_PreprocessingDirective:
1559 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001560 case CXCursor_MacroDefinition:
1561 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001562 case CXCursor_MacroInstantiation:
1563 return createCXString("macro instantiation");
Steve Naroff89922f82009-08-31 00:59:03 +00001564 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001565
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001566 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001567 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001568}
Steve Naroff89922f82009-08-31 00:59:03 +00001569
Ted Kremeneke68fff62010-02-17 00:41:32 +00001570enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1571 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001572 CXClientData client_data) {
1573 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1574 *BestCursor = cursor;
1575 return CXChildVisit_Recurse;
1576}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001577
Douglas Gregorb9790342010-01-22 21:44:22 +00001578CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1579 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001580 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001581
Douglas Gregorb9790342010-01-22 21:44:22 +00001582 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1583
Douglas Gregorbdf60622010-03-05 21:16:25 +00001584 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1585
Ted Kremeneka297de22010-01-25 22:34:44 +00001586 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001587 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1588 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001589 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001590
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001591 // FIXME: Would be great to have a "hint" cursor, then walk from that
1592 // hint cursor upward until we find a cursor whose source range encloses
1593 // the region of interest, rather than starting from the translation unit.
1594 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001595 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001596 Decl::MaxPCHLevel, RegionOfInterest);
1597 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001598 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001599 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001600}
1601
Ted Kremenek73885552009-11-17 19:28:59 +00001602CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001603 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001604}
1605
1606unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001607 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001608}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001609
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001610unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001611 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1612}
1613
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001614unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001615 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1616}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001617
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001618unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001619 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1620}
1621
Douglas Gregor97b98722010-01-19 23:20:36 +00001622unsigned clang_isExpression(enum CXCursorKind K) {
1623 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1624}
1625
1626unsigned clang_isStatement(enum CXCursorKind K) {
1627 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1628}
1629
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001630unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1631 return K == CXCursor_TranslationUnit;
1632}
1633
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001634unsigned clang_isPreprocessing(enum CXCursorKind K) {
1635 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1636}
1637
Ted Kremenekad6eff62010-03-08 21:17:29 +00001638unsigned clang_isUnexposed(enum CXCursorKind K) {
1639 switch (K) {
1640 case CXCursor_UnexposedDecl:
1641 case CXCursor_UnexposedExpr:
1642 case CXCursor_UnexposedStmt:
1643 case CXCursor_UnexposedAttr:
1644 return true;
1645 default:
1646 return false;
1647 }
1648}
1649
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001650CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001651 return C.kind;
1652}
1653
Douglas Gregor98258af2010-01-18 22:46:11 +00001654CXSourceLocation clang_getCursorLocation(CXCursor C) {
1655 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001656 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001657 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001658 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1659 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001660 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001661 }
1662
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001663 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001664 std::pair<ObjCProtocolDecl *, SourceLocation> P
1665 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001666 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001667 }
1668
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001669 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001670 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1671 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001672 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001673 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001674
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001675 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001676 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001677 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001678 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001679
Douglas Gregorf46034a2010-01-18 23:41:10 +00001680 default:
1681 // FIXME: Need a way to enumerate all non-reference cases.
1682 llvm_unreachable("Missed a reference kind");
1683 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001684 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001685
1686 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001687 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001688 getLocationFromExpr(getCursorExpr(C)));
1689
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001690 if (C.kind == CXCursor_PreprocessingDirective) {
1691 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1692 return cxloc::translateSourceLocation(getCursorContext(C), L);
1693 }
Douglas Gregor48072312010-03-18 15:23:44 +00001694
1695 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001696 SourceLocation L
1697 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001698 return cxloc::translateSourceLocation(getCursorContext(C), L);
1699 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001700
1701 if (C.kind == CXCursor_MacroDefinition) {
1702 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1703 return cxloc::translateSourceLocation(getCursorContext(C), L);
1704 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001705
Douglas Gregor5352ac02010-01-28 00:27:43 +00001706 if (!getCursorDecl(C))
1707 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001708
Douglas Gregorf46034a2010-01-18 23:41:10 +00001709 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001710 SourceLocation Loc = D->getLocation();
1711 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1712 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001713 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001714}
Douglas Gregora7bde202010-01-19 00:34:46 +00001715
1716CXSourceRange clang_getCursorExtent(CXCursor C) {
1717 if (clang_isReference(C.kind)) {
1718 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001719 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001720 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1721 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001722 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001723 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001724
1725 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001726 std::pair<ObjCProtocolDecl *, SourceLocation> P
1727 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001728 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001729 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001730
1731 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001732 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1733 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001734
Ted Kremeneka297de22010-01-25 22:34:44 +00001735 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001736 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001737
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001738 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001739 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001740 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001741 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001742
Douglas Gregora7bde202010-01-19 00:34:46 +00001743 default:
1744 // FIXME: Need a way to enumerate all non-reference cases.
1745 llvm_unreachable("Missed a reference kind");
1746 }
1747 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001748
1749 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001750 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001751 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001752
1753 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001754 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001755 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001756
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001757 if (C.kind == CXCursor_PreprocessingDirective) {
1758 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1759 return cxloc::translateSourceRange(getCursorContext(C), R);
1760 }
Douglas Gregor48072312010-03-18 15:23:44 +00001761
1762 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001763 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001764 return cxloc::translateSourceRange(getCursorContext(C), R);
1765 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001766
1767 if (C.kind == CXCursor_MacroDefinition) {
1768 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1769 return cxloc::translateSourceRange(getCursorContext(C), R);
1770 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001771
Douglas Gregor5352ac02010-01-28 00:27:43 +00001772 if (!getCursorDecl(C))
1773 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001774
Douglas Gregora7bde202010-01-19 00:34:46 +00001775 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001776 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001777}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001778
1779CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001780 if (clang_isInvalid(C.kind))
1781 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001782
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001783 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001784 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001785 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001786
Douglas Gregor97b98722010-01-19 23:20:36 +00001787 if (clang_isExpression(C.kind)) {
1788 Decl *D = getDeclFromExpr(getCursorExpr(C));
1789 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001790 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001791 return clang_getNullCursor();
1792 }
1793
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001794 if (C.kind == CXCursor_MacroInstantiation) {
1795 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1796 return MakeMacroDefinitionCursor(Def, CXXUnit);
1797 }
1798
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001799 if (!clang_isReference(C.kind))
1800 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001801
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001802 switch (C.kind) {
1803 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001804 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001805
1806 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001807 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001808
1809 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001810 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001811
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001812 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001813 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001814
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001815 default:
1816 // We would prefer to enumerate all non-reference cursor kinds here.
1817 llvm_unreachable("Unhandled reference cursor kind");
1818 break;
1819 }
1820 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001821
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001822 return clang_getNullCursor();
1823}
1824
Douglas Gregorb6998662010-01-19 19:34:47 +00001825CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001826 if (clang_isInvalid(C.kind))
1827 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001828
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001829 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001830
Douglas Gregorb6998662010-01-19 19:34:47 +00001831 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001832 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001833 C = clang_getCursorReferenced(C);
1834 WasReference = true;
1835 }
1836
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001837 if (C.kind == CXCursor_MacroInstantiation)
1838 return clang_getCursorReferenced(C);
1839
Douglas Gregorb6998662010-01-19 19:34:47 +00001840 if (!clang_isDeclaration(C.kind))
1841 return clang_getNullCursor();
1842
1843 Decl *D = getCursorDecl(C);
1844 if (!D)
1845 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001846
Douglas Gregorb6998662010-01-19 19:34:47 +00001847 switch (D->getKind()) {
1848 // Declaration kinds that don't really separate the notions of
1849 // declaration and definition.
1850 case Decl::Namespace:
1851 case Decl::Typedef:
1852 case Decl::TemplateTypeParm:
1853 case Decl::EnumConstant:
1854 case Decl::Field:
1855 case Decl::ObjCIvar:
1856 case Decl::ObjCAtDefsField:
1857 case Decl::ImplicitParam:
1858 case Decl::ParmVar:
1859 case Decl::NonTypeTemplateParm:
1860 case Decl::TemplateTemplateParm:
1861 case Decl::ObjCCategoryImpl:
1862 case Decl::ObjCImplementation:
1863 case Decl::LinkageSpec:
1864 case Decl::ObjCPropertyImpl:
1865 case Decl::FileScopeAsm:
1866 case Decl::StaticAssert:
1867 case Decl::Block:
1868 return C;
1869
1870 // Declaration kinds that don't make any sense here, but are
1871 // nonetheless harmless.
1872 case Decl::TranslationUnit:
1873 case Decl::Template:
1874 case Decl::ObjCContainer:
1875 break;
1876
1877 // Declaration kinds for which the definition is not resolvable.
1878 case Decl::UnresolvedUsingTypename:
1879 case Decl::UnresolvedUsingValue:
1880 break;
1881
1882 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001883 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1884 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001885
1886 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001887 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001888
1889 case Decl::Enum:
1890 case Decl::Record:
1891 case Decl::CXXRecord:
1892 case Decl::ClassTemplateSpecialization:
1893 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001894 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001895 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001896 return clang_getNullCursor();
1897
1898 case Decl::Function:
1899 case Decl::CXXMethod:
1900 case Decl::CXXConstructor:
1901 case Decl::CXXDestructor:
1902 case Decl::CXXConversion: {
1903 const FunctionDecl *Def = 0;
1904 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001905 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001906 return clang_getNullCursor();
1907 }
1908
1909 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001910 // Ask the variable if it has a definition.
1911 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1912 return MakeCXCursor(Def, CXXUnit);
1913 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001914 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001915
Douglas Gregorb6998662010-01-19 19:34:47 +00001916 case Decl::FunctionTemplate: {
1917 const FunctionDecl *Def = 0;
1918 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001919 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001920 return clang_getNullCursor();
1921 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001922
Douglas Gregorb6998662010-01-19 19:34:47 +00001923 case Decl::ClassTemplate: {
1924 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001925 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001926 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001927 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001928 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001929 return clang_getNullCursor();
1930 }
1931
1932 case Decl::Using: {
1933 UsingDecl *Using = cast<UsingDecl>(D);
1934 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001935 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1936 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001937 S != SEnd; ++S) {
1938 if (Def != clang_getNullCursor()) {
1939 // FIXME: We have no way to return multiple results.
1940 return clang_getNullCursor();
1941 }
1942
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001943 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001944 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001945 }
1946
1947 return Def;
1948 }
1949
1950 case Decl::UsingShadow:
1951 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001952 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001953 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001954
1955 case Decl::ObjCMethod: {
1956 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1957 if (Method->isThisDeclarationADefinition())
1958 return C;
1959
1960 // Dig out the method definition in the associated
1961 // @implementation, if we have it.
1962 // FIXME: The ASTs should make finding the definition easier.
1963 if (ObjCInterfaceDecl *Class
1964 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1965 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1966 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1967 Method->isInstanceMethod()))
1968 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001969 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001970
1971 return clang_getNullCursor();
1972 }
1973
1974 case Decl::ObjCCategory:
1975 if (ObjCCategoryImplDecl *Impl
1976 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001977 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001978 return clang_getNullCursor();
1979
1980 case Decl::ObjCProtocol:
1981 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1982 return C;
1983 return clang_getNullCursor();
1984
1985 case Decl::ObjCInterface:
1986 // There are two notions of a "definition" for an Objective-C
1987 // class: the interface and its implementation. When we resolved a
1988 // reference to an Objective-C class, produce the @interface as
1989 // the definition; when we were provided with the interface,
1990 // produce the @implementation as the definition.
1991 if (WasReference) {
1992 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1993 return C;
1994 } else if (ObjCImplementationDecl *Impl
1995 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001996 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001997 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001998
Douglas Gregorb6998662010-01-19 19:34:47 +00001999 case Decl::ObjCProperty:
2000 // FIXME: We don't really know where to find the
2001 // ObjCPropertyImplDecls that implement this property.
2002 return clang_getNullCursor();
2003
2004 case Decl::ObjCCompatibleAlias:
2005 if (ObjCInterfaceDecl *Class
2006 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2007 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002008 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002009
Douglas Gregorb6998662010-01-19 19:34:47 +00002010 return clang_getNullCursor();
2011
2012 case Decl::ObjCForwardProtocol: {
2013 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2014 if (Forward->protocol_size() == 1)
2015 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002016 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002017 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002018
2019 // FIXME: Cannot return multiple definitions.
2020 return clang_getNullCursor();
2021 }
2022
2023 case Decl::ObjCClass: {
2024 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2025 if (Class->size() == 1) {
2026 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2027 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002028 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002029 return clang_getNullCursor();
2030 }
2031
2032 // FIXME: Cannot return multiple definitions.
2033 return clang_getNullCursor();
2034 }
2035
2036 case Decl::Friend:
2037 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002038 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002039 return clang_getNullCursor();
2040
2041 case Decl::FriendTemplate:
2042 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002043 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002044 return clang_getNullCursor();
2045 }
2046
2047 return clang_getNullCursor();
2048}
2049
2050unsigned clang_isCursorDefinition(CXCursor C) {
2051 if (!clang_isDeclaration(C.kind))
2052 return 0;
2053
2054 return clang_getCursorDefinition(C) == C;
2055}
2056
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002057void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002058 const char **startBuf,
2059 const char **endBuf,
2060 unsigned *startLine,
2061 unsigned *startColumn,
2062 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002063 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002064 assert(getCursorDecl(C) && "CXCursor has null decl");
2065 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002066 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2067 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002068
Steve Naroff4ade6d62009-09-23 17:52:52 +00002069 SourceManager &SM = FD->getASTContext().getSourceManager();
2070 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2071 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2072 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2073 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2074 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2075 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2076}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002077
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002078void clang_enableStackTraces(void) {
2079 llvm::sys::PrintStackTraceOnErrorSignal();
2080}
2081
Ted Kremenekfb480492010-01-13 21:46:36 +00002082} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002083
Ted Kremenekfb480492010-01-13 21:46:36 +00002084//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002085// Token-based Operations.
2086//===----------------------------------------------------------------------===//
2087
2088/* CXToken layout:
2089 * int_data[0]: a CXTokenKind
2090 * int_data[1]: starting token location
2091 * int_data[2]: token length
2092 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002093 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002094 * otherwise unused.
2095 */
2096extern "C" {
2097
2098CXTokenKind clang_getTokenKind(CXToken CXTok) {
2099 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2100}
2101
2102CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2103 switch (clang_getTokenKind(CXTok)) {
2104 case CXToken_Identifier:
2105 case CXToken_Keyword:
2106 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002107 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2108 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002109
2110 case CXToken_Literal: {
2111 // We have stashed the starting pointer in the ptr_data field. Use it.
2112 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002113 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002114 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002115
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002116 case CXToken_Punctuation:
2117 case CXToken_Comment:
2118 break;
2119 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002120
2121 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002122 // deconstructing the source location.
2123 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2124 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002125 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002126
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002127 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2128 std::pair<FileID, unsigned> LocInfo
2129 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002130 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002131 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002132 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2133 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002134 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002135
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002136 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002137}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002138
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002139CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2140 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2141 if (!CXXUnit)
2142 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002143
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002144 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2145 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2146}
2147
2148CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2149 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002150 if (!CXXUnit)
2151 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002152
2153 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002154 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2155}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002156
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002157void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2158 CXToken **Tokens, unsigned *NumTokens) {
2159 if (Tokens)
2160 *Tokens = 0;
2161 if (NumTokens)
2162 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002163
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002164 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2165 if (!CXXUnit || !Tokens || !NumTokens)
2166 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002167
Douglas Gregorbdf60622010-03-05 21:16:25 +00002168 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2169
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002170 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002171 if (R.isInvalid())
2172 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002173
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002174 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2175 std::pair<FileID, unsigned> BeginLocInfo
2176 = SourceMgr.getDecomposedLoc(R.getBegin());
2177 std::pair<FileID, unsigned> EndLocInfo
2178 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002179
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002180 // Cannot tokenize across files.
2181 if (BeginLocInfo.first != EndLocInfo.first)
2182 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002183
2184 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002185 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002186 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002187 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002188 if (Invalid)
2189 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002190
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002191 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2192 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002193 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002194 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002195
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002196 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002197 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002198 llvm::SmallVector<CXToken, 32> CXTokens;
2199 Token Tok;
2200 do {
2201 // Lex the next token
2202 Lex.LexFromRawLexer(Tok);
2203 if (Tok.is(tok::eof))
2204 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002205
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002206 // Initialize the CXToken.
2207 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002208
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002209 // - Common fields
2210 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2211 CXTok.int_data[2] = Tok.getLength();
2212 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002213
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002214 // - Kind-specific fields
2215 if (Tok.isLiteral()) {
2216 CXTok.int_data[0] = CXToken_Literal;
2217 CXTok.ptr_data = (void *)Tok.getLiteralData();
2218 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002219 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002220 std::pair<FileID, unsigned> LocInfo
2221 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002222 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002223 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002224 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2225 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002226 return;
2227
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002228 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002229 IdentifierInfo *II
2230 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2231 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2232 CXToken_Identifier
2233 : CXToken_Keyword;
2234 CXTok.ptr_data = II;
2235 } else if (Tok.is(tok::comment)) {
2236 CXTok.int_data[0] = CXToken_Comment;
2237 CXTok.ptr_data = 0;
2238 } else {
2239 CXTok.int_data[0] = CXToken_Punctuation;
2240 CXTok.ptr_data = 0;
2241 }
2242 CXTokens.push_back(CXTok);
2243 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002244
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002245 if (CXTokens.empty())
2246 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002247
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002248 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2249 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2250 *NumTokens = CXTokens.size();
2251}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002252
2253typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2254
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002255enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2256 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002257 CXClientData client_data) {
2258 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2259
2260 // We only annotate the locations of declarations, simple
2261 // references, and expressions which directly reference something.
2262 CXCursorKind Kind = clang_getCursorKind(cursor);
2263 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2264 // Okay: We can annotate the location of this declaration with the
2265 // declaration or reference
2266 } else if (clang_isExpression(cursor.kind)) {
2267 if (Kind != CXCursor_DeclRefExpr &&
2268 Kind != CXCursor_MemberRefExpr &&
2269 Kind != CXCursor_ObjCMessageExpr)
2270 return CXChildVisit_Recurse;
2271
2272 CXCursor Referenced = clang_getCursorReferenced(cursor);
2273 if (Referenced == cursor || Referenced == clang_getNullCursor())
2274 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002275
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002276 // Okay: we can annotate the location of this expression
Douglas Gregor0396f462010-03-19 05:22:59 +00002277 } else if (clang_isPreprocessing(cursor.kind)) {
2278 // We can always annotate a preprocessing directive/macro instantiation.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002279 } else {
2280 // Nothing to annotate
2281 return CXChildVisit_Recurse;
2282 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002283
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002284 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2285 (*Data)[Loc.int_data] = cursor;
2286 return CXChildVisit_Recurse;
2287}
2288
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002289void clang_annotateTokens(CXTranslationUnit TU,
2290 CXToken *Tokens, unsigned NumTokens,
2291 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002292 if (NumTokens == 0)
2293 return;
2294
2295 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002296 for (unsigned I = 0; I != NumTokens; ++I)
2297 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002298
2299 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2300 if (!CXXUnit || !Tokens)
2301 return;
2302
Douglas Gregorbdf60622010-03-05 21:16:25 +00002303 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2304
Douglas Gregor0396f462010-03-19 05:22:59 +00002305 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002306 SourceRange RegionOfInterest;
2307 RegionOfInterest.setBegin(
2308 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2309 SourceLocation End
Douglas Gregor0396f462010-03-19 05:22:59 +00002310 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2311 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002312 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor2507fa82010-03-19 00:18:31 +00002313
Douglas Gregor0396f462010-03-19 05:22:59 +00002314 // A mapping from the source locations found when re-lexing or traversing the
2315 // region of interest to the corresponding cursors.
2316 AnnotateTokensData Annotated;
2317
2318 // Relex the tokens within the source range to look for preprocessing
2319 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002320 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2321 std::pair<FileID, unsigned> BeginLocInfo
2322 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2323 std::pair<FileID, unsigned> EndLocInfo
2324 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2325
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002326 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002327 bool Invalid = false;
2328 if (BeginLocInfo.first == EndLocInfo.first &&
2329 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2330 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002331 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2332 CXXUnit->getASTContext().getLangOptions(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002333 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2334 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002335 Lex.SetCommentRetentionState(true);
2336
2337 // Lex tokens in raw mode until we hit the end of the range, to avoid
2338 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002339 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002340 Token Tok;
2341 Lex.LexFromRawLexer(Tok);
2342
2343 reprocess:
2344 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2345 // We have found a preprocessing directive. Gobble it up so that we
2346 // don't see it while preprocessing these tokens later, but keep track of
2347 // all of the token locations inside this preprocessing directive so that
2348 // we can annotate them appropriately.
2349 //
2350 // FIXME: Some simple tests here could identify macro definitions and
2351 // #undefs, to provide specific cursor kinds for those.
2352 std::vector<SourceLocation> Locations;
2353 do {
2354 Locations.push_back(Tok.getLocation());
2355 Lex.LexFromRawLexer(Tok);
2356 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2357
2358 using namespace cxcursor;
2359 CXCursor Cursor
2360 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2361 Locations.back()),
2362 CXXUnit);
2363 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2364 Annotated[Locations[I].getRawEncoding()] = Cursor;
2365 }
2366
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002367 if (Tok.isAtStartOfLine())
2368 goto reprocess;
2369
2370 continue;
2371 }
2372
Douglas Gregor48072312010-03-18 15:23:44 +00002373 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002374 break;
2375 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002376 }
Douglas Gregor0396f462010-03-19 05:22:59 +00002377
2378 // Annotate all of the source locations in the region of interest that map to
2379 // a specific cursor.
2380 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2381 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2382 Decl::MaxPCHLevel, RegionOfInterest);
2383 AnnotateVis.VisitChildren(Parent);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002384
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002385 for (unsigned I = 0; I != NumTokens; ++I) {
2386 // Determine whether we saw a cursor at this token's location.
2387 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2388 if (Pos == Annotated.end())
2389 continue;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002390
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002391 Cursors[I] = Pos->second;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002392 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002393}
2394
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002395void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002396 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002397 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002398}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002399
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002400} // end: extern "C"
2401
2402//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002403// Operations for querying linkage of a cursor.
2404//===----------------------------------------------------------------------===//
2405
2406extern "C" {
2407CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002408 if (!clang_isDeclaration(cursor.kind))
2409 return CXLinkage_Invalid;
2410
Ted Kremenek16b42592010-03-03 06:36:57 +00002411 Decl *D = cxcursor::getCursorDecl(cursor);
2412 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2413 switch (ND->getLinkage()) {
2414 case NoLinkage: return CXLinkage_NoLinkage;
2415 case InternalLinkage: return CXLinkage_Internal;
2416 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2417 case ExternalLinkage: return CXLinkage_External;
2418 };
2419
2420 return CXLinkage_Invalid;
2421}
2422} // end: extern "C"
2423
2424//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002425// CXString Operations.
2426//===----------------------------------------------------------------------===//
2427
2428extern "C" {
2429const char *clang_getCString(CXString string) {
2430 return string.Spelling;
2431}
2432
2433void clang_disposeString(CXString string) {
2434 if (string.MustFreeString && string.Spelling)
2435 free((void*)string.Spelling);
2436}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002437
Ted Kremenekfb480492010-01-13 21:46:36 +00002438} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002439
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002440namespace clang { namespace cxstring {
2441CXString createCXString(const char *String, bool DupString){
2442 CXString Str;
2443 if (DupString) {
2444 Str.Spelling = strdup(String);
2445 Str.MustFreeString = 1;
2446 } else {
2447 Str.Spelling = String;
2448 Str.MustFreeString = 0;
2449 }
2450 return Str;
2451}
2452
2453CXString createCXString(llvm::StringRef String, bool DupString) {
2454 CXString Result;
2455 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2456 char *Spelling = (char *)malloc(String.size() + 1);
2457 memmove(Spelling, String.data(), String.size());
2458 Spelling[String.size()] = 0;
2459 Result.Spelling = Spelling;
2460 Result.MustFreeString = 1;
2461 } else {
2462 Result.Spelling = String.data();
2463 Result.MustFreeString = 0;
2464 }
2465 return Result;
2466}
2467}}
2468
Ted Kremenek04bb7162010-01-22 22:44:15 +00002469//===----------------------------------------------------------------------===//
2470// Misc. utility functions.
2471//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002472
Ted Kremenek04bb7162010-01-22 22:44:15 +00002473extern "C" {
2474
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002475CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002476 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002477}
2478
2479} // end: extern "C"