blob: ce2188550bd28a8e1fc4a5f0ad9c0a8917b3d832 [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 }
428 } else {
429 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000430 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000431 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000432
Douglas Gregor7b691f332010-01-20 21:13:59 +0000433 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000435
Douglas Gregorb1373d02010-01-20 20:59:29 +0000436 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000437 return false;
438}
439
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000441 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000442 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000443
Daniel Dunbard52864b2010-02-14 10:02:57 +0000444 CXCursor Cursor = MakeCXCursor(*I, TU);
445
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000446 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000447 SourceRange Range =
448 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
449 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000450 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000451
452 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000453 case RangeBefore:
454 // This declaration comes before the region of interest; skip it.
455 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000456
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000457 case RangeAfter:
458 // This declaration comes after the region of interest; we're done.
459 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000460
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000461 case RangeOverlap:
462 // This declaration overlaps the region of interest; visit it.
463 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000464 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000465 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000466
Daniel Dunbard52864b2010-02-14 10:02:57 +0000467 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468 return true;
469 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000470
Douglas Gregorb1373d02010-01-20 20:59:29 +0000471 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000472}
473
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000474bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
475 llvm_unreachable("Translation units are visited directly by Visit()");
476 return false;
477}
478
479bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
480 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
481 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000482
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000483 return false;
484}
485
486bool CursorVisitor::VisitTagDecl(TagDecl *D) {
487 return VisitDeclContext(D);
488}
489
490bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
491 if (Expr *Init = D->getInitExpr())
492 return Visit(MakeCXCursor(Init, StmtParent, TU));
493 return false;
494}
495
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000496bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
497 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
498 if (Visit(TSInfo->getTypeLoc()))
499 return true;
500
501 return false;
502}
503
Douglas Gregorb1373d02010-01-20 20:59:29 +0000504bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000505 if (VisitDeclaratorDecl(ND))
506 return true;
507
Douglas Gregora59e3902010-01-21 23:27:09 +0000508 if (ND->isThisDeclarationADefinition() &&
509 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
510 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000511
Douglas Gregorb1373d02010-01-20 20:59:29 +0000512 return false;
513}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000514
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000515bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
516 if (VisitDeclaratorDecl(D))
517 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000518
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000519 if (Expr *BitWidth = D->getBitWidth())
520 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000521
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000522 return false;
523}
524
525bool CursorVisitor::VisitVarDecl(VarDecl *D) {
526 if (VisitDeclaratorDecl(D))
527 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000528
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000529 if (Expr *Init = D->getInit())
530 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000531
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000532 return false;
533}
534
535bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000536 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
537 if (Visit(TSInfo->getTypeLoc()))
538 return true;
539
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000540 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000541 PEnd = ND->param_end();
542 P != PEnd; ++P) {
543 if (Visit(MakeCXCursor(*P, TU)))
544 return true;
545 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000546
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000547 if (ND->isThisDeclarationADefinition() &&
548 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
549 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000550
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000551 return false;
552}
553
Douglas Gregora59e3902010-01-21 23:27:09 +0000554bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
555 return VisitDeclContext(D);
556}
557
Douglas Gregorb1373d02010-01-20 20:59:29 +0000558bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000559 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
560 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000561 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000562
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000563 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
564 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
565 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000566 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000567 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000568
Douglas Gregora59e3902010-01-21 23:27:09 +0000569 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000570}
571
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000572bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
573 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
574 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
575 E = PID->protocol_end(); I != E; ++I, ++PL)
576 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
577 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000578
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000579 return VisitObjCContainerDecl(PID);
580}
581
Douglas Gregorb1373d02010-01-20 20:59:29 +0000582bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000583 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000584 if (D->getSuperClass() &&
585 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000586 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000587 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000588 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000589
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000590 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
591 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
592 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000593 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000594 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000595
Douglas Gregora59e3902010-01-21 23:27:09 +0000596 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000597}
598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
600 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000601}
602
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000603bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000604 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000605 D->getLocation(), TU)))
606 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000607
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000608 return VisitObjCImplDecl(D);
609}
610
611bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
612#if 0
613 // Issue callbacks for super class.
614 // FIXME: No source location information!
615 if (D->getSuperClass() &&
616 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000617 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000618 TU)))
619 return true;
620#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000621
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000622 return VisitObjCImplDecl(D);
623}
624
625bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
626 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
627 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
628 E = D->protocol_end();
629 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000630 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000631 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000632
633 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000634}
635
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000636bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
637 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
638 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
639 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000640
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000641 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000642}
643
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000644bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
645 ASTContext &Context = TU->getASTContext();
646
647 // Some builtin types (such as Objective-C's "id", "sel", and
648 // "Class") have associated declarations. Create cursors for those.
649 QualType VisitType;
650 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000651 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000652 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000653 case BuiltinType::Char_U:
654 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000655 case BuiltinType::Char16:
656 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000657 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000658 case BuiltinType::UInt:
659 case BuiltinType::ULong:
660 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000661 case BuiltinType::UInt128:
662 case BuiltinType::Char_S:
663 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000664 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000665 case BuiltinType::Short:
666 case BuiltinType::Int:
667 case BuiltinType::Long:
668 case BuiltinType::LongLong:
669 case BuiltinType::Int128:
670 case BuiltinType::Float:
671 case BuiltinType::Double:
672 case BuiltinType::LongDouble:
673 case BuiltinType::NullPtr:
674 case BuiltinType::Overload:
675 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000676 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000677
678 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000679 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000680
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000681 case BuiltinType::ObjCId:
682 VisitType = Context.getObjCIdType();
683 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000684
685 case BuiltinType::ObjCClass:
686 VisitType = Context.getObjCClassType();
687 break;
688
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000689 case BuiltinType::ObjCSel:
690 VisitType = Context.getObjCSelType();
691 break;
692 }
693
694 if (!VisitType.isNull()) {
695 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000696 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000697 TU));
698 }
699
700 return false;
701}
702
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000703bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
704 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
705}
706
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000707bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
708 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
709}
710
711bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
712 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
713}
714
715bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
716 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
717 return true;
718
719 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
720 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
721 TU)))
722 return true;
723 }
724
725 return false;
726}
727
728bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
729 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
730 return true;
731
732 if (TL.hasProtocolsAsWritten()) {
733 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000734 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000735 TL.getProtocolLoc(I),
736 TU)))
737 return true;
738 }
739 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000740
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000741 return false;
742}
743
744bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
745 return Visit(TL.getPointeeLoc());
746}
747
748bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
749 return Visit(TL.getPointeeLoc());
750}
751
752bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
753 return Visit(TL.getPointeeLoc());
754}
755
756bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000757 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000758}
759
760bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000761 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000762}
763
764bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
765 if (Visit(TL.getResultLoc()))
766 return true;
767
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000768 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
769 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
770 return true;
771
772 return false;
773}
774
775bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
776 if (Visit(TL.getElementLoc()))
777 return true;
778
779 if (Expr *Size = TL.getSizeExpr())
780 return Visit(MakeCXCursor(Size, StmtParent, TU));
781
782 return false;
783}
784
Douglas Gregor2332c112010-01-21 20:48:56 +0000785bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
786 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
787}
788
789bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
790 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
791 return Visit(TSInfo->getTypeLoc());
792
793 return false;
794}
795
Douglas Gregora59e3902010-01-21 23:27:09 +0000796bool CursorVisitor::VisitStmt(Stmt *S) {
797 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
798 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000799 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000800 return true;
801 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000802
Douglas Gregora59e3902010-01-21 23:27:09 +0000803 return false;
804}
805
806bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
807 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
808 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000809 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000810 return true;
811 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000812
Douglas Gregora59e3902010-01-21 23:27:09 +0000813 return false;
814}
815
Douglas Gregorf5bab412010-01-22 01:00:11 +0000816bool CursorVisitor::VisitIfStmt(IfStmt *S) {
817 if (VarDecl *Var = S->getConditionVariable()) {
818 if (Visit(MakeCXCursor(Var, TU)))
819 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000820 }
821
Douglas Gregor263b47b2010-01-25 16:12:32 +0000822 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
823 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000824 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
825 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000826 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
827 return true;
828
829 return false;
830}
831
832bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
833 if (VarDecl *Var = S->getConditionVariable()) {
834 if (Visit(MakeCXCursor(Var, TU)))
835 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000836 }
837
Douglas Gregor263b47b2010-01-25 16:12:32 +0000838 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
839 return true;
840 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
841 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000842
Douglas Gregor263b47b2010-01-25 16:12:32 +0000843 return false;
844}
845
846bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
847 if (VarDecl *Var = S->getConditionVariable()) {
848 if (Visit(MakeCXCursor(Var, TU)))
849 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000850 }
851
Douglas Gregor263b47b2010-01-25 16:12:32 +0000852 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
853 return true;
854 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000855 return true;
856
Douglas Gregor263b47b2010-01-25 16:12:32 +0000857 return false;
858}
859
860bool CursorVisitor::VisitForStmt(ForStmt *S) {
861 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
862 return true;
863 if (VarDecl *Var = S->getConditionVariable()) {
864 if (Visit(MakeCXCursor(Var, TU)))
865 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000866 }
867
Douglas Gregor263b47b2010-01-25 16:12:32 +0000868 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
869 return true;
870 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
871 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000872 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
873 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000874
Douglas Gregorf5bab412010-01-22 01:00:11 +0000875 return false;
876}
877
Douglas Gregor336fd812010-01-23 00:40:08 +0000878bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
879 if (E->isArgumentType()) {
880 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
881 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000882
Douglas Gregor336fd812010-01-23 00:40:08 +0000883 return false;
884 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000885
Douglas Gregor336fd812010-01-23 00:40:08 +0000886 return VisitExpr(E);
887}
888
889bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
890 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
891 if (Visit(TSInfo->getTypeLoc()))
892 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000893
Douglas Gregor336fd812010-01-23 00:40:08 +0000894 return VisitCastExpr(E);
895}
896
897bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
898 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
899 if (Visit(TSInfo->getTypeLoc()))
900 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000901
Douglas Gregor336fd812010-01-23 00:40:08 +0000902 return VisitExpr(E);
903}
904
Douglas Gregorc2350e52010-03-08 16:40:19 +0000905bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
906 ObjCMessageExpr::ClassInfo CI = E->getClassInfo();
907 if (CI.Decl && Visit(MakeCursorObjCClassRef(CI.Decl, CI.Loc, TU)))
908 return true;
909
910 return VisitExpr(E);
911}
912
Ted Kremenek09dfa372010-02-18 05:46:33 +0000913bool CursorVisitor::VisitAttributes(Decl *D) {
914 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
915 if (Visit(MakeCXCursor(A, D, TU)))
916 return true;
917
918 return false;
919}
920
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000921extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000922CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
923 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000924 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000925 if (excludeDeclarationsFromPCH)
926 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000927 if (displayDiagnostics)
928 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000929 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000930}
931
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000932void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000933 if (CIdx)
934 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000935}
936
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000937void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000938 if (CIdx) {
939 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
940 CXXIdx->setUseExternalASTGeneration(value);
941 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000942}
943
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000944CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +0000945 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000946 if (!CIdx)
947 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000948
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000949 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000950
Douglas Gregor5352ac02010-01-28 00:27:43 +0000951 // Configure the diagnostics.
952 DiagnosticOptions DiagOpts;
953 llvm::OwningPtr<Diagnostic> Diags;
954 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Douglas Gregor5352ac02010-01-28 00:27:43 +0000955 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +0000956 CXXIdx->getOnlyLocalDecls(),
957 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +0000958}
959
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000960CXTranslationUnit
961clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
962 const char *source_filename,
963 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000964 const char **command_line_args,
965 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +0000966 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000967 if (!CIdx)
968 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000969
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000970 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
971
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));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000976
Douglas Gregor4db64a42010-01-23 00:14:00 +0000977 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
978 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000979 const llvm::MemoryBuffer *Buffer
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000980 = llvm::MemoryBuffer::getMemBufferCopy(unsaved_files[I].Contents,
Douglas Gregor313e26c2010-02-18 23:35:40 +0000981 unsaved_files[I].Contents + unsaved_files[I].Length,
982 unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000983 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
984 Buffer));
985 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000986
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000987 if (!CXXIdx->getUseExternalASTGeneration()) {
988 llvm::SmallVector<const char *, 16> Args;
989
990 // The 'source_filename' argument is optional. If the caller does not
991 // specify it then it is assumed that the source file is specified
992 // in the actual argument list.
993 if (source_filename)
994 Args.push_back(source_filename);
995 Args.insert(Args.end(), command_line_args,
996 command_line_args + num_command_line_args);
997
Douglas Gregor5352ac02010-01-28 00:27:43 +0000998 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000999
Ted Kremenek29b72842010-01-07 22:49:05 +00001000#ifdef USE_CRASHTRACER
1001 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001002#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001003
Daniel Dunbar94220972009-12-05 02:17:18 +00001004 llvm::OwningPtr<ASTUnit> Unit(
1005 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001006 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001007 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001008 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001009 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001010 RemappedFiles.size(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001011 /*CaptureDiagnostics=*/true,
1012 /*WantPreprocessingRecord=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001013
Daniel Dunbar94220972009-12-05 02:17:18 +00001014 // FIXME: Until we have broader testing, just drop the entire AST if we
1015 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001016 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001017 // Make sure to check that 'Unit' is non-NULL.
1018 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001019 for (ASTUnit::diag_iterator D = Unit->diag_begin(),
1020 DEnd = Unit->diag_end();
1021 D != DEnd; ++D) {
1022 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001023 CXString Msg = clang_formatDiagnostic(&Diag,
1024 clang_defaultDiagnosticDisplayOptions());
1025 fprintf(stderr, "%s\n", clang_getCString(Msg));
1026 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001027 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001028#ifdef LLVM_ON_WIN32
1029 // On Windows, force a flush, since there may be multiple copies of
1030 // stderr and stdout in the file system, all with different buffers
1031 // but writing to the same device.
1032 fflush(stderr);
1033#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001034 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001035 return 0;
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001036 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001037
1038 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001039 }
1040
Ted Kremenek139ba862009-10-22 00:03:57 +00001041 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001042 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001043
Ted Kremenek139ba862009-10-22 00:03:57 +00001044 // First add the complete path to the 'clang' executable.
1045 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001046 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001047
Ted Kremenek139ba862009-10-22 00:03:57 +00001048 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001049 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001050
Ted Kremenek139ba862009-10-22 00:03:57 +00001051 // The 'source_filename' argument is optional. If the caller does not
1052 // specify it then it is assumed that the source file is specified
1053 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001054 if (source_filename)
1055 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001056
Steve Naroff37b5ac22009-10-15 20:50:09 +00001057 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001058 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001059 char astTmpFile[L_tmpnam];
1060 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001061
Douglas Gregor4db64a42010-01-23 00:14:00 +00001062 // Remap any unsaved files to temporary files.
1063 std::vector<llvm::sys::Path> TemporaryFiles;
1064 std::vector<std::string> RemapArgs;
1065 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1066 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001067
Douglas Gregor4db64a42010-01-23 00:14:00 +00001068 // The pointers into the elements of RemapArgs are stable because we
1069 // won't be adding anything to RemapArgs after this point.
1070 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1071 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001072
Ted Kremenek139ba862009-10-22 00:03:57 +00001073 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1074 for (int i = 0; i < num_command_line_args; ++i)
1075 if (const char *arg = command_line_args[i]) {
1076 if (strcmp(arg, "-o") == 0) {
1077 ++i; // Also skip the matching argument.
1078 continue;
1079 }
1080 if (strcmp(arg, "-emit-ast") == 0 ||
1081 strcmp(arg, "-c") == 0 ||
1082 strcmp(arg, "-fsyntax-only") == 0) {
1083 continue;
1084 }
1085
1086 // Keep the argument.
1087 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001088 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001089
Douglas Gregord93256e2010-01-28 06:00:51 +00001090 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001091 char tmpFileResults[L_tmpnam];
1092 char *tmpResultsFileName = tmpnam(tmpFileResults);
1093 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001094 TemporaryFiles.push_back(DiagnosticsFile);
1095 argv.push_back("-fdiagnostics-binary");
1096
Ted Kremenek139ba862009-10-22 00:03:57 +00001097 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001098 argv.push_back(NULL);
1099
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001100 // Invoke 'clang'.
1101 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1102 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001103 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001104 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1105 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001106 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001107 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001108 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001109
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001110 if (!ErrMsg.empty()) {
1111 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001112 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001113 I != E; ++I) {
1114 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001115 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001116 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001117 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001118
Daniel Dunbar32141c82010-02-23 20:23:45 +00001119 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001120 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001121
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001122 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001123 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001124 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001125 RemappedFiles.size(),
1126 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001127 if (ATU) {
1128 LoadSerializedDiagnostics(DiagnosticsFile,
1129 num_unsaved_files, unsaved_files,
1130 ATU->getFileManager(),
1131 ATU->getSourceManager(),
1132 ATU->getDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001133 } else if (CXXIdx->getDisplayDiagnostics()) {
1134 // We failed to load the ASTUnit, but we can still deserialize the
1135 // diagnostics and emit them.
1136 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001137 Diagnostic Diag;
1138 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001139 // FIXME: Faked LangOpts!
1140 LangOptions LangOpts;
1141 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1142 LoadSerializedDiagnostics(DiagnosticsFile,
1143 num_unsaved_files, unsaved_files,
1144 FileMgr, SourceMgr, Diags);
1145 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1146 DEnd = Diags.end();
1147 D != DEnd; ++D) {
1148 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001149 CXString Msg = clang_formatDiagnostic(&Diag,
1150 clang_defaultDiagnosticDisplayOptions());
1151 fprintf(stderr, "%s\n", clang_getCString(Msg));
1152 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001153 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001154
1155#ifdef LLVM_ON_WIN32
1156 // On Windows, force a flush, since there may be multiple copies of
1157 // stderr and stdout in the file system, all with different buffers
1158 // but writing to the same device.
1159 fflush(stderr);
1160#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001161 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001162
Douglas Gregor313e26c2010-02-18 23:35:40 +00001163 if (ATU) {
1164 // Make the translation unit responsible for destroying all temporary files.
1165 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1166 ATU->addTemporaryFile(TemporaryFiles[i]);
1167 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1168 } else {
1169 // Destroy all of the temporary files now; they can't be referenced any
1170 // longer.
1171 llvm::sys::Path(astTmpFile).eraseFromDisk();
1172 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1173 TemporaryFiles[i].eraseFromDisk();
1174 }
1175
Steve Naroffe19944c2009-10-15 22:23:48 +00001176 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001177}
1178
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001179void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001180 if (CTUnit)
1181 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001182}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001183
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001184CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001185 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001186 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001187
Steve Naroff77accc12009-09-03 18:19:54 +00001188 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001189 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001190}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001191
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001192CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001193 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001194 return Result;
1195}
1196
Ted Kremenekfb480492010-01-13 21:46:36 +00001197} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001198
Ted Kremenekfb480492010-01-13 21:46:36 +00001199//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001200// CXSourceLocation and CXSourceRange Operations.
1201//===----------------------------------------------------------------------===//
1202
Douglas Gregorb9790342010-01-22 21:44:22 +00001203extern "C" {
1204CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001205 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001206 return Result;
1207}
1208
1209unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001210 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1211 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1212 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001213}
1214
1215CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1216 CXFile file,
1217 unsigned line,
1218 unsigned column) {
1219 if (!tu)
1220 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001221
Douglas Gregorb9790342010-01-22 21:44:22 +00001222 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1223 SourceLocation SLoc
1224 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001225 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001226 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001227
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001228 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001229}
1230
Douglas Gregor5352ac02010-01-28 00:27:43 +00001231CXSourceRange clang_getNullRange() {
1232 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1233 return Result;
1234}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001235
Douglas Gregor5352ac02010-01-28 00:27:43 +00001236CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1237 if (begin.ptr_data[0] != end.ptr_data[0] ||
1238 begin.ptr_data[1] != end.ptr_data[1])
1239 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001240
1241 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001242 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001243 return Result;
1244}
1245
Douglas Gregor46766dc2010-01-26 19:19:08 +00001246void clang_getInstantiationLocation(CXSourceLocation location,
1247 CXFile *file,
1248 unsigned *line,
1249 unsigned *column,
1250 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001251 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1252
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001253 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001254 if (file)
1255 *file = 0;
1256 if (line)
1257 *line = 0;
1258 if (column)
1259 *column = 0;
1260 if (offset)
1261 *offset = 0;
1262 return;
1263 }
1264
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001265 const SourceManager &SM =
1266 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001267 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001268
1269 if (file)
1270 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1271 if (line)
1272 *line = SM.getInstantiationLineNumber(InstLoc);
1273 if (column)
1274 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001275 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001276 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001277}
1278
Douglas Gregor1db19de2010-01-19 21:36:55 +00001279CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001280 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001281 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001282 return Result;
1283}
1284
1285CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001286 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001287 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001288 return Result;
1289}
1290
Douglas Gregorb9790342010-01-22 21:44:22 +00001291} // end: extern "C"
1292
Douglas Gregor1db19de2010-01-19 21:36:55 +00001293//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001294// CXFile Operations.
1295//===----------------------------------------------------------------------===//
1296
1297extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001298CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001299 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001300 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001301
Steve Naroff88145032009-10-27 14:35:18 +00001302 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001303 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001304}
1305
1306time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001307 if (!SFile)
1308 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001309
Steve Naroff88145032009-10-27 14:35:18 +00001310 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1311 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001312}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001313
Douglas Gregorb9790342010-01-22 21:44:22 +00001314CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1315 if (!tu)
1316 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001317
Douglas Gregorb9790342010-01-22 21:44:22 +00001318 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001319
Douglas Gregorb9790342010-01-22 21:44:22 +00001320 FileManager &FMgr = CXXUnit->getFileManager();
1321 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1322 return const_cast<FileEntry *>(File);
1323}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001324
Ted Kremenekfb480492010-01-13 21:46:36 +00001325} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001326
Ted Kremenekfb480492010-01-13 21:46:36 +00001327//===----------------------------------------------------------------------===//
1328// CXCursor Operations.
1329//===----------------------------------------------------------------------===//
1330
Ted Kremenekfb480492010-01-13 21:46:36 +00001331static Decl *getDeclFromExpr(Stmt *E) {
1332 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1333 return RefExpr->getDecl();
1334 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1335 return ME->getMemberDecl();
1336 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1337 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001338
Ted Kremenekfb480492010-01-13 21:46:36 +00001339 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1340 return getDeclFromExpr(CE->getCallee());
1341 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1342 return getDeclFromExpr(CE->getSubExpr());
1343 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1344 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001345
Ted Kremenekfb480492010-01-13 21:46:36 +00001346 return 0;
1347}
1348
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001349static SourceLocation getLocationFromExpr(Expr *E) {
1350 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1351 return /*FIXME:*/Msg->getLeftLoc();
1352 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1353 return DRE->getLocation();
1354 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1355 return Member->getMemberLoc();
1356 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1357 return Ivar->getLocation();
1358 return E->getLocStart();
1359}
1360
Ted Kremenekfb480492010-01-13 21:46:36 +00001361extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001362
1363unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001364 CXCursorVisitor visitor,
1365 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001366 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001367
1368 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001369
Douglas Gregorb1373d02010-01-20 20:59:29 +00001370 // Set the PCHLevel to filter out unwanted decls if requested.
1371 if (CXXUnit->getOnlyLocalDecls()) {
1372 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001373
Douglas Gregorb1373d02010-01-20 20:59:29 +00001374 // If the main input was an AST, bump the level.
1375 if (CXXUnit->isMainFileAST())
1376 ++PCHLevel;
1377 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001378
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001379 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001380 return CursorVis.VisitChildren(parent);
1381}
1382
Douglas Gregor78205d42010-01-20 21:45:58 +00001383static CXString getDeclSpelling(Decl *D) {
1384 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1385 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001386 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001387
Douglas Gregor78205d42010-01-20 21:45:58 +00001388 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001389 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001390
Douglas Gregor78205d42010-01-20 21:45:58 +00001391 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1392 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1393 // and returns different names. NamedDecl returns the class name and
1394 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001395 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001396
Douglas Gregor78205d42010-01-20 21:45:58 +00001397 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001398 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001399
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001400 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001401}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001402
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001403CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001404 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001405 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001406
Steve Narofff334b4e2009-09-02 18:26:48 +00001407 if (clang_isReference(C.kind)) {
1408 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001409 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001410 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001411 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001412 }
1413 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001414 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001415 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001416 }
1417 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001418 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001419 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001420 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001421 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001422 case CXCursor_TypeRef: {
1423 TypeDecl *Type = getCursorTypeRef(C).first;
1424 assert(Type && "Missing type decl");
1425
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001426 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1427 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001428 }
1429
Daniel Dunbaracca7252009-11-30 20:42:49 +00001430 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001431 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001432 }
1433 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001434
1435 if (clang_isExpression(C.kind)) {
1436 Decl *D = getDeclFromExpr(getCursorExpr(C));
1437 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001438 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001439 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001440 }
1441
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001442 if (C.kind == CXCursor_MacroInstantiation)
1443 return createCXString(getCursorMacroInstantiation(C)->getName()
1444 ->getNameStart());
1445
Douglas Gregor572feb22010-03-18 18:04:21 +00001446 if (C.kind == CXCursor_MacroDefinition)
1447 return createCXString(getCursorMacroDefinition(C)->getName()
1448 ->getNameStart());
1449
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001450 if (clang_isDeclaration(C.kind))
1451 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001452
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001453 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001454}
1455
Ted Kremeneke68fff62010-02-17 00:41:32 +00001456CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001457 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001458 case CXCursor_FunctionDecl:
1459 return createCXString("FunctionDecl");
1460 case CXCursor_TypedefDecl:
1461 return createCXString("TypedefDecl");
1462 case CXCursor_EnumDecl:
1463 return createCXString("EnumDecl");
1464 case CXCursor_EnumConstantDecl:
1465 return createCXString("EnumConstantDecl");
1466 case CXCursor_StructDecl:
1467 return createCXString("StructDecl");
1468 case CXCursor_UnionDecl:
1469 return createCXString("UnionDecl");
1470 case CXCursor_ClassDecl:
1471 return createCXString("ClassDecl");
1472 case CXCursor_FieldDecl:
1473 return createCXString("FieldDecl");
1474 case CXCursor_VarDecl:
1475 return createCXString("VarDecl");
1476 case CXCursor_ParmDecl:
1477 return createCXString("ParmDecl");
1478 case CXCursor_ObjCInterfaceDecl:
1479 return createCXString("ObjCInterfaceDecl");
1480 case CXCursor_ObjCCategoryDecl:
1481 return createCXString("ObjCCategoryDecl");
1482 case CXCursor_ObjCProtocolDecl:
1483 return createCXString("ObjCProtocolDecl");
1484 case CXCursor_ObjCPropertyDecl:
1485 return createCXString("ObjCPropertyDecl");
1486 case CXCursor_ObjCIvarDecl:
1487 return createCXString("ObjCIvarDecl");
1488 case CXCursor_ObjCInstanceMethodDecl:
1489 return createCXString("ObjCInstanceMethodDecl");
1490 case CXCursor_ObjCClassMethodDecl:
1491 return createCXString("ObjCClassMethodDecl");
1492 case CXCursor_ObjCImplementationDecl:
1493 return createCXString("ObjCImplementationDecl");
1494 case CXCursor_ObjCCategoryImplDecl:
1495 return createCXString("ObjCCategoryImplDecl");
1496 case CXCursor_UnexposedDecl:
1497 return createCXString("UnexposedDecl");
1498 case CXCursor_ObjCSuperClassRef:
1499 return createCXString("ObjCSuperClassRef");
1500 case CXCursor_ObjCProtocolRef:
1501 return createCXString("ObjCProtocolRef");
1502 case CXCursor_ObjCClassRef:
1503 return createCXString("ObjCClassRef");
1504 case CXCursor_TypeRef:
1505 return createCXString("TypeRef");
1506 case CXCursor_UnexposedExpr:
1507 return createCXString("UnexposedExpr");
1508 case CXCursor_DeclRefExpr:
1509 return createCXString("DeclRefExpr");
1510 case CXCursor_MemberRefExpr:
1511 return createCXString("MemberRefExpr");
1512 case CXCursor_CallExpr:
1513 return createCXString("CallExpr");
1514 case CXCursor_ObjCMessageExpr:
1515 return createCXString("ObjCMessageExpr");
1516 case CXCursor_UnexposedStmt:
1517 return createCXString("UnexposedStmt");
1518 case CXCursor_InvalidFile:
1519 return createCXString("InvalidFile");
1520 case CXCursor_NoDeclFound:
1521 return createCXString("NoDeclFound");
1522 case CXCursor_NotImplemented:
1523 return createCXString("NotImplemented");
1524 case CXCursor_TranslationUnit:
1525 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001526 case CXCursor_UnexposedAttr:
1527 return createCXString("UnexposedAttr");
1528 case CXCursor_IBActionAttr:
1529 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001530 case CXCursor_IBOutletAttr:
1531 return createCXString("attribute(iboutlet)");
1532 case CXCursor_PreprocessingDirective:
1533 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001534 case CXCursor_MacroDefinition:
1535 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001536 case CXCursor_MacroInstantiation:
1537 return createCXString("macro instantiation");
Steve Naroff89922f82009-08-31 00:59:03 +00001538 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001539
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001540 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001541 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001542}
Steve Naroff89922f82009-08-31 00:59:03 +00001543
Ted Kremeneke68fff62010-02-17 00:41:32 +00001544enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1545 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001546 CXClientData client_data) {
1547 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1548 *BestCursor = cursor;
1549 return CXChildVisit_Recurse;
1550}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001551
Douglas Gregorb9790342010-01-22 21:44:22 +00001552CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1553 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001554 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001555
Douglas Gregorb9790342010-01-22 21:44:22 +00001556 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1557
Douglas Gregorbdf60622010-03-05 21:16:25 +00001558 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1559
Ted Kremeneka297de22010-01-25 22:34:44 +00001560 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001561 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1562 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001563 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001564
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001565 // FIXME: Would be great to have a "hint" cursor, then walk from that
1566 // hint cursor upward until we find a cursor whose source range encloses
1567 // the region of interest, rather than starting from the translation unit.
1568 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001569 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001570 Decl::MaxPCHLevel, RegionOfInterest);
1571 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001572 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001573 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001574}
1575
Ted Kremenek73885552009-11-17 19:28:59 +00001576CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001577 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001578}
1579
1580unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001581 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001582}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001583
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001584unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001585 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1586}
1587
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001588unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001589 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1590}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001591
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001592unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001593 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1594}
1595
Douglas Gregor97b98722010-01-19 23:20:36 +00001596unsigned clang_isExpression(enum CXCursorKind K) {
1597 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1598}
1599
1600unsigned clang_isStatement(enum CXCursorKind K) {
1601 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1602}
1603
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001604unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1605 return K == CXCursor_TranslationUnit;
1606}
1607
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001608unsigned clang_isPreprocessing(enum CXCursorKind K) {
1609 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1610}
1611
Ted Kremenekad6eff62010-03-08 21:17:29 +00001612unsigned clang_isUnexposed(enum CXCursorKind K) {
1613 switch (K) {
1614 case CXCursor_UnexposedDecl:
1615 case CXCursor_UnexposedExpr:
1616 case CXCursor_UnexposedStmt:
1617 case CXCursor_UnexposedAttr:
1618 return true;
1619 default:
1620 return false;
1621 }
1622}
1623
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001624CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001625 return C.kind;
1626}
1627
Douglas Gregor98258af2010-01-18 22:46:11 +00001628CXSourceLocation clang_getCursorLocation(CXCursor C) {
1629 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001630 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001631 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001632 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1633 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001634 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001635 }
1636
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001637 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001638 std::pair<ObjCProtocolDecl *, SourceLocation> P
1639 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001640 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001641 }
1642
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001643 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001644 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1645 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001646 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001647 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001648
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001649 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001650 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001651 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001652 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001653
Douglas Gregorf46034a2010-01-18 23:41:10 +00001654 default:
1655 // FIXME: Need a way to enumerate all non-reference cases.
1656 llvm_unreachable("Missed a reference kind");
1657 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001658 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001659
1660 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001661 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001662 getLocationFromExpr(getCursorExpr(C)));
1663
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001664 if (C.kind == CXCursor_PreprocessingDirective) {
1665 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1666 return cxloc::translateSourceLocation(getCursorContext(C), L);
1667 }
Douglas Gregor48072312010-03-18 15:23:44 +00001668
1669 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001670 SourceLocation L
1671 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001672 return cxloc::translateSourceLocation(getCursorContext(C), L);
1673 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001674
1675 if (C.kind == CXCursor_MacroDefinition) {
1676 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1677 return cxloc::translateSourceLocation(getCursorContext(C), L);
1678 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001679
Douglas Gregor5352ac02010-01-28 00:27:43 +00001680 if (!getCursorDecl(C))
1681 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001682
Douglas Gregorf46034a2010-01-18 23:41:10 +00001683 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001684 SourceLocation Loc = D->getLocation();
1685 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1686 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001687 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001688}
Douglas Gregora7bde202010-01-19 00:34:46 +00001689
1690CXSourceRange clang_getCursorExtent(CXCursor C) {
1691 if (clang_isReference(C.kind)) {
1692 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001693 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001694 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1695 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001696 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001697 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001698
1699 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001700 std::pair<ObjCProtocolDecl *, SourceLocation> P
1701 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001702 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001703 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001704
1705 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001706 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1707 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001708
Ted Kremeneka297de22010-01-25 22:34:44 +00001709 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001710 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001711
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001712 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001713 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001714 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001715 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001716
Douglas Gregora7bde202010-01-19 00:34:46 +00001717 default:
1718 // FIXME: Need a way to enumerate all non-reference cases.
1719 llvm_unreachable("Missed a reference kind");
1720 }
1721 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001722
1723 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001724 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001725 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001726
1727 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001728 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001729 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001730
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001731 if (C.kind == CXCursor_PreprocessingDirective) {
1732 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1733 return cxloc::translateSourceRange(getCursorContext(C), R);
1734 }
Douglas Gregor48072312010-03-18 15:23:44 +00001735
1736 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001737 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001738 return cxloc::translateSourceRange(getCursorContext(C), R);
1739 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001740
1741 if (C.kind == CXCursor_MacroDefinition) {
1742 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1743 return cxloc::translateSourceRange(getCursorContext(C), R);
1744 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001745
Douglas Gregor5352ac02010-01-28 00:27:43 +00001746 if (!getCursorDecl(C))
1747 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001748
Douglas Gregora7bde202010-01-19 00:34:46 +00001749 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001750 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001751}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001752
1753CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001754 if (clang_isInvalid(C.kind))
1755 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001756
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001757 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001758 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001759 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001760
Douglas Gregor97b98722010-01-19 23:20:36 +00001761 if (clang_isExpression(C.kind)) {
1762 Decl *D = getDeclFromExpr(getCursorExpr(C));
1763 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001764 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001765 return clang_getNullCursor();
1766 }
1767
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001768 if (!clang_isReference(C.kind))
1769 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001770
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001771 switch (C.kind) {
1772 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001773 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001774
1775 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001776 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001777
1778 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001779 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001780
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001781 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001782 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001783
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001784 default:
1785 // We would prefer to enumerate all non-reference cursor kinds here.
1786 llvm_unreachable("Unhandled reference cursor kind");
1787 break;
1788 }
1789 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001790
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001791 return clang_getNullCursor();
1792}
1793
Douglas Gregorb6998662010-01-19 19:34:47 +00001794CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001795 if (clang_isInvalid(C.kind))
1796 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001797
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001798 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001799
Douglas Gregorb6998662010-01-19 19:34:47 +00001800 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001801 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001802 C = clang_getCursorReferenced(C);
1803 WasReference = true;
1804 }
1805
1806 if (!clang_isDeclaration(C.kind))
1807 return clang_getNullCursor();
1808
1809 Decl *D = getCursorDecl(C);
1810 if (!D)
1811 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001812
Douglas Gregorb6998662010-01-19 19:34:47 +00001813 switch (D->getKind()) {
1814 // Declaration kinds that don't really separate the notions of
1815 // declaration and definition.
1816 case Decl::Namespace:
1817 case Decl::Typedef:
1818 case Decl::TemplateTypeParm:
1819 case Decl::EnumConstant:
1820 case Decl::Field:
1821 case Decl::ObjCIvar:
1822 case Decl::ObjCAtDefsField:
1823 case Decl::ImplicitParam:
1824 case Decl::ParmVar:
1825 case Decl::NonTypeTemplateParm:
1826 case Decl::TemplateTemplateParm:
1827 case Decl::ObjCCategoryImpl:
1828 case Decl::ObjCImplementation:
1829 case Decl::LinkageSpec:
1830 case Decl::ObjCPropertyImpl:
1831 case Decl::FileScopeAsm:
1832 case Decl::StaticAssert:
1833 case Decl::Block:
1834 return C;
1835
1836 // Declaration kinds that don't make any sense here, but are
1837 // nonetheless harmless.
1838 case Decl::TranslationUnit:
1839 case Decl::Template:
1840 case Decl::ObjCContainer:
1841 break;
1842
1843 // Declaration kinds for which the definition is not resolvable.
1844 case Decl::UnresolvedUsingTypename:
1845 case Decl::UnresolvedUsingValue:
1846 break;
1847
1848 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001849 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1850 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001851
1852 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001853 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001854
1855 case Decl::Enum:
1856 case Decl::Record:
1857 case Decl::CXXRecord:
1858 case Decl::ClassTemplateSpecialization:
1859 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001860 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001861 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001862 return clang_getNullCursor();
1863
1864 case Decl::Function:
1865 case Decl::CXXMethod:
1866 case Decl::CXXConstructor:
1867 case Decl::CXXDestructor:
1868 case Decl::CXXConversion: {
1869 const FunctionDecl *Def = 0;
1870 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001871 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001872 return clang_getNullCursor();
1873 }
1874
1875 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001876 // Ask the variable if it has a definition.
1877 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1878 return MakeCXCursor(Def, CXXUnit);
1879 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001880 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001881
Douglas Gregorb6998662010-01-19 19:34:47 +00001882 case Decl::FunctionTemplate: {
1883 const FunctionDecl *Def = 0;
1884 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001885 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001886 return clang_getNullCursor();
1887 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001888
Douglas Gregorb6998662010-01-19 19:34:47 +00001889 case Decl::ClassTemplate: {
1890 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001891 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001892 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001893 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001894 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001895 return clang_getNullCursor();
1896 }
1897
1898 case Decl::Using: {
1899 UsingDecl *Using = cast<UsingDecl>(D);
1900 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001901 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1902 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001903 S != SEnd; ++S) {
1904 if (Def != clang_getNullCursor()) {
1905 // FIXME: We have no way to return multiple results.
1906 return clang_getNullCursor();
1907 }
1908
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001909 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001910 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001911 }
1912
1913 return Def;
1914 }
1915
1916 case Decl::UsingShadow:
1917 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001918 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001919 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001920
1921 case Decl::ObjCMethod: {
1922 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1923 if (Method->isThisDeclarationADefinition())
1924 return C;
1925
1926 // Dig out the method definition in the associated
1927 // @implementation, if we have it.
1928 // FIXME: The ASTs should make finding the definition easier.
1929 if (ObjCInterfaceDecl *Class
1930 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1931 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1932 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1933 Method->isInstanceMethod()))
1934 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001935 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001936
1937 return clang_getNullCursor();
1938 }
1939
1940 case Decl::ObjCCategory:
1941 if (ObjCCategoryImplDecl *Impl
1942 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001943 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001944 return clang_getNullCursor();
1945
1946 case Decl::ObjCProtocol:
1947 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1948 return C;
1949 return clang_getNullCursor();
1950
1951 case Decl::ObjCInterface:
1952 // There are two notions of a "definition" for an Objective-C
1953 // class: the interface and its implementation. When we resolved a
1954 // reference to an Objective-C class, produce the @interface as
1955 // the definition; when we were provided with the interface,
1956 // produce the @implementation as the definition.
1957 if (WasReference) {
1958 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1959 return C;
1960 } else if (ObjCImplementationDecl *Impl
1961 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001962 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001963 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001964
Douglas Gregorb6998662010-01-19 19:34:47 +00001965 case Decl::ObjCProperty:
1966 // FIXME: We don't really know where to find the
1967 // ObjCPropertyImplDecls that implement this property.
1968 return clang_getNullCursor();
1969
1970 case Decl::ObjCCompatibleAlias:
1971 if (ObjCInterfaceDecl *Class
1972 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1973 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001974 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001975
Douglas Gregorb6998662010-01-19 19:34:47 +00001976 return clang_getNullCursor();
1977
1978 case Decl::ObjCForwardProtocol: {
1979 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1980 if (Forward->protocol_size() == 1)
1981 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001982 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001983 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001984
1985 // FIXME: Cannot return multiple definitions.
1986 return clang_getNullCursor();
1987 }
1988
1989 case Decl::ObjCClass: {
1990 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1991 if (Class->size() == 1) {
1992 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1993 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001994 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001995 return clang_getNullCursor();
1996 }
1997
1998 // FIXME: Cannot return multiple definitions.
1999 return clang_getNullCursor();
2000 }
2001
2002 case Decl::Friend:
2003 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002004 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002005 return clang_getNullCursor();
2006
2007 case Decl::FriendTemplate:
2008 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002009 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002010 return clang_getNullCursor();
2011 }
2012
2013 return clang_getNullCursor();
2014}
2015
2016unsigned clang_isCursorDefinition(CXCursor C) {
2017 if (!clang_isDeclaration(C.kind))
2018 return 0;
2019
2020 return clang_getCursorDefinition(C) == C;
2021}
2022
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002023void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002024 const char **startBuf,
2025 const char **endBuf,
2026 unsigned *startLine,
2027 unsigned *startColumn,
2028 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002029 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002030 assert(getCursorDecl(C) && "CXCursor has null decl");
2031 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002032 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2033 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002034
Steve Naroff4ade6d62009-09-23 17:52:52 +00002035 SourceManager &SM = FD->getASTContext().getSourceManager();
2036 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2037 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2038 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2039 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2040 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2041 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2042}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002043
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002044void clang_enableStackTraces(void) {
2045 llvm::sys::PrintStackTraceOnErrorSignal();
2046}
2047
Ted Kremenekfb480492010-01-13 21:46:36 +00002048} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002049
Ted Kremenekfb480492010-01-13 21:46:36 +00002050//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002051// Token-based Operations.
2052//===----------------------------------------------------------------------===//
2053
Douglas Gregor48072312010-03-18 15:23:44 +00002054namespace {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002055 class ComparePreprocessedEntityLocation {
2056 SourceManager &SM;
2057
2058 public:
2059 explicit ComparePreprocessedEntityLocation(SourceManager &SM) : SM(SM) { }
2060
2061 bool operator()(const PreprocessedEntity *Entity, SourceLocation Loc) {
2062 return SM.isBeforeInTranslationUnit(Entity->getSourceRange().getEnd(),
2063 Loc);
2064 }
2065
2066 bool operator()(SourceLocation Loc, const PreprocessedEntity *Entity) {
2067 return SM.isBeforeInTranslationUnit(Loc,
2068 Entity->getSourceRange().getBegin());
2069 }
2070
2071 bool operator()(const PreprocessedEntity *Entity, SourceRange R) {
2072 return SM.isBeforeInTranslationUnit(Entity->getSourceRange().getEnd(),
2073 R.getBegin());
2074 }
2075
2076 bool operator()(SourceRange R, const PreprocessedEntity *Entity) {
2077 return SM.isBeforeInTranslationUnit(R.getEnd(),
2078 Entity->getSourceRange().getBegin());
2079 }
2080 };
Douglas Gregor48072312010-03-18 15:23:44 +00002081}
2082
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002083
2084
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002085/* CXToken layout:
2086 * int_data[0]: a CXTokenKind
2087 * int_data[1]: starting token location
2088 * int_data[2]: token length
2089 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002090 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002091 * otherwise unused.
2092 */
2093extern "C" {
2094
2095CXTokenKind clang_getTokenKind(CXToken CXTok) {
2096 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2097}
2098
2099CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2100 switch (clang_getTokenKind(CXTok)) {
2101 case CXToken_Identifier:
2102 case CXToken_Keyword:
2103 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002104 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2105 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002106
2107 case CXToken_Literal: {
2108 // We have stashed the starting pointer in the ptr_data field. Use it.
2109 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002110 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002111 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002112
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002113 case CXToken_Punctuation:
2114 case CXToken_Comment:
2115 break;
2116 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002117
2118 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002119 // deconstructing the source location.
2120 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2121 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002122 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002123
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002124 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2125 std::pair<FileID, unsigned> LocInfo
2126 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002127 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002128 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002129 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2130 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002131 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002132
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002133 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002134}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002135
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002136CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2137 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2138 if (!CXXUnit)
2139 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002140
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002141 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2142 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2143}
2144
2145CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2146 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002147 if (!CXXUnit)
2148 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002149
2150 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002151 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2152}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002153
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002154void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2155 CXToken **Tokens, unsigned *NumTokens) {
2156 if (Tokens)
2157 *Tokens = 0;
2158 if (NumTokens)
2159 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002160
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002161 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2162 if (!CXXUnit || !Tokens || !NumTokens)
2163 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002164
Douglas Gregorbdf60622010-03-05 21:16:25 +00002165 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2166
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002167 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002168 if (R.isInvalid())
2169 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002170
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002171 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2172 std::pair<FileID, unsigned> BeginLocInfo
2173 = SourceMgr.getDecomposedLoc(R.getBegin());
2174 std::pair<FileID, unsigned> EndLocInfo
2175 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002176
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002177 // Cannot tokenize across files.
2178 if (BeginLocInfo.first != EndLocInfo.first)
2179 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002180
2181 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002182 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002183 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002184 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002185 if (Invalid)
2186 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002187
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002188 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2189 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002190 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002191 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002192
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002193 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002194 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002195 llvm::SmallVector<CXToken, 32> CXTokens;
2196 Token Tok;
2197 do {
2198 // Lex the next token
2199 Lex.LexFromRawLexer(Tok);
2200 if (Tok.is(tok::eof))
2201 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002202
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002203 // Initialize the CXToken.
2204 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002205
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002206 // - Common fields
2207 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2208 CXTok.int_data[2] = Tok.getLength();
2209 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002210
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002211 // - Kind-specific fields
2212 if (Tok.isLiteral()) {
2213 CXTok.int_data[0] = CXToken_Literal;
2214 CXTok.ptr_data = (void *)Tok.getLiteralData();
2215 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002216 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002217 std::pair<FileID, unsigned> LocInfo
2218 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002219 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002220 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002221 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2222 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002223 return;
2224
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002225 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002226 IdentifierInfo *II
2227 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2228 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2229 CXToken_Identifier
2230 : CXToken_Keyword;
2231 CXTok.ptr_data = II;
2232 } else if (Tok.is(tok::comment)) {
2233 CXTok.int_data[0] = CXToken_Comment;
2234 CXTok.ptr_data = 0;
2235 } else {
2236 CXTok.int_data[0] = CXToken_Punctuation;
2237 CXTok.ptr_data = 0;
2238 }
2239 CXTokens.push_back(CXTok);
2240 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002241
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002242 if (CXTokens.empty())
2243 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002244
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002245 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2246 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2247 *NumTokens = CXTokens.size();
2248}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002249
2250typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2251
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002252enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2253 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002254 CXClientData client_data) {
2255 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2256
2257 // We only annotate the locations of declarations, simple
2258 // references, and expressions which directly reference something.
2259 CXCursorKind Kind = clang_getCursorKind(cursor);
2260 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2261 // Okay: We can annotate the location of this declaration with the
2262 // declaration or reference
2263 } else if (clang_isExpression(cursor.kind)) {
2264 if (Kind != CXCursor_DeclRefExpr &&
2265 Kind != CXCursor_MemberRefExpr &&
2266 Kind != CXCursor_ObjCMessageExpr)
2267 return CXChildVisit_Recurse;
2268
2269 CXCursor Referenced = clang_getCursorReferenced(cursor);
2270 if (Referenced == cursor || Referenced == clang_getNullCursor())
2271 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002272
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002273 // Okay: we can annotate the location of this expression
2274 } else {
2275 // Nothing to annotate
2276 return CXChildVisit_Recurse;
2277 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002278
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002279 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2280 (*Data)[Loc.int_data] = cursor;
2281 return CXChildVisit_Recurse;
2282}
2283
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002284void clang_annotateTokens(CXTranslationUnit TU,
2285 CXToken *Tokens, unsigned NumTokens,
2286 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002287 if (NumTokens == 0)
2288 return;
2289
2290 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002291 for (unsigned I = 0; I != NumTokens; ++I)
2292 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002293
2294 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2295 if (!CXXUnit || !Tokens)
2296 return;
2297
Douglas Gregorbdf60622010-03-05 21:16:25 +00002298 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2299
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002300 // Annotate all of the source locations in the region of interest that map to
2301 // a specific cursor.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002302 SourceRange RegionOfInterest;
2303 RegionOfInterest.setBegin(
2304 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2305 SourceLocation End
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002306 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002307 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002308 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002309
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002310 AnnotateTokensData Annotated;
2311 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002312 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002313 Decl::MaxPCHLevel, RegionOfInterest);
2314 AnnotateVis.VisitChildren(Parent);
2315
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002316 // Look for macro instantiations and preprocessing directives in the
2317 // source range containing the annotated tokens. We do this by re-lexing the
2318 // tokens in the source range.
2319 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2320 std::pair<FileID, unsigned> BeginLocInfo
2321 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2322 std::pair<FileID, unsigned> EndLocInfo
2323 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2324
2325 bool RelexOkay = true;
2326
2327 // Cannot re-tokenize across files.
2328 if (BeginLocInfo.first != EndLocInfo.first)
2329 RelexOkay = false;
2330
2331 llvm::StringRef Buffer;
2332 if (RelexOkay) {
2333 // Create a lexer
2334 bool Invalid = false;
2335 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
2336 if (Invalid)
2337 RelexOkay = false;
2338 }
2339
2340 if (RelexOkay) {
2341 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2342 CXXUnit->getASTContext().getLangOptions(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002343 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2344 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002345 Lex.SetCommentRetentionState(true);
2346
2347 // Lex tokens in raw mode until we hit the end of the range, to avoid
2348 // entering #includes or expanding macros.
2349 std::vector<Token> TokenStream;
Douglas Gregor48072312010-03-18 15:23:44 +00002350 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002351 Token Tok;
2352 Lex.LexFromRawLexer(Tok);
2353
2354 reprocess:
2355 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2356 // We have found a preprocessing directive. Gobble it up so that we
2357 // don't see it while preprocessing these tokens later, but keep track of
2358 // all of the token locations inside this preprocessing directive so that
2359 // we can annotate them appropriately.
2360 //
2361 // FIXME: Some simple tests here could identify macro definitions and
2362 // #undefs, to provide specific cursor kinds for those.
2363 std::vector<SourceLocation> Locations;
2364 do {
2365 Locations.push_back(Tok.getLocation());
2366 Lex.LexFromRawLexer(Tok);
2367 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2368
2369 using namespace cxcursor;
2370 CXCursor Cursor
2371 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2372 Locations.back()),
2373 CXXUnit);
2374 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2375 Annotated[Locations[I].getRawEncoding()] = Cursor;
2376 }
2377
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002378 if (Tok.isAtStartOfLine())
2379 goto reprocess;
2380
2381 continue;
2382 }
2383
Douglas Gregor48072312010-03-18 15:23:44 +00002384 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002385 break;
2386 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002387 }
2388
2389 if (CXXUnit->hasPreprocessingRecord()) {
2390 PreprocessingRecord &PPRec = CXXUnit->getPreprocessingRecord();
2391 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2392 Entities = std::equal_range(PPRec.begin(), PPRec.end(), RegionOfInterest,
2393 ComparePreprocessedEntityLocation(SourceMgr));
2394 for (; Entities.first != Entities.second; ++Entities.first) {
2395 PreprocessedEntity *Entity = *Entities.first;
2396 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(Entity)) {
2397 SourceLocation Loc = MI->getSourceRange().getBegin();
2398 if (Loc.isFileID()) {
2399 Annotated[Loc.getRawEncoding()]
2400 = MakeMacroInstantiationCursor(MI, CXXUnit);
2401 }
Douglas Gregor48072312010-03-18 15:23:44 +00002402
Douglas Gregor48072312010-03-18 15:23:44 +00002403 continue;
2404 }
2405
Douglas Gregor572feb22010-03-18 18:04:21 +00002406 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(Entity)) {
2407 SourceLocation Loc = MD->getLocation();
2408 if (Loc.isFileID()) {
2409 Annotated[Loc.getRawEncoding()]
2410 = MakeMacroDefinitionCursor(MD, CXXUnit);
2411 }
2412
2413 continue;
2414 }
Douglas Gregor48072312010-03-18 15:23:44 +00002415 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002416 }
2417
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002418 for (unsigned I = 0; I != NumTokens; ++I) {
2419 // Determine whether we saw a cursor at this token's location.
2420 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2421 if (Pos == Annotated.end())
2422 continue;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002423
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002424 Cursors[I] = Pos->second;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002425 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002426}
2427
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002428void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002429 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002430 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002431}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002432
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002433} // end: extern "C"
2434
2435//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002436// Operations for querying linkage of a cursor.
2437//===----------------------------------------------------------------------===//
2438
2439extern "C" {
2440CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
2441 Decl *D = cxcursor::getCursorDecl(cursor);
2442 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2443 switch (ND->getLinkage()) {
2444 case NoLinkage: return CXLinkage_NoLinkage;
2445 case InternalLinkage: return CXLinkage_Internal;
2446 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2447 case ExternalLinkage: return CXLinkage_External;
2448 };
2449
2450 return CXLinkage_Invalid;
2451}
2452} // end: extern "C"
2453
2454//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002455// CXString Operations.
2456//===----------------------------------------------------------------------===//
2457
2458extern "C" {
2459const char *clang_getCString(CXString string) {
2460 return string.Spelling;
2461}
2462
2463void clang_disposeString(CXString string) {
2464 if (string.MustFreeString && string.Spelling)
2465 free((void*)string.Spelling);
2466}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002467
Ted Kremenekfb480492010-01-13 21:46:36 +00002468} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002469
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002470namespace clang { namespace cxstring {
2471CXString createCXString(const char *String, bool DupString){
2472 CXString Str;
2473 if (DupString) {
2474 Str.Spelling = strdup(String);
2475 Str.MustFreeString = 1;
2476 } else {
2477 Str.Spelling = String;
2478 Str.MustFreeString = 0;
2479 }
2480 return Str;
2481}
2482
2483CXString createCXString(llvm::StringRef String, bool DupString) {
2484 CXString Result;
2485 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2486 char *Spelling = (char *)malloc(String.size() + 1);
2487 memmove(Spelling, String.data(), String.size());
2488 Spelling[String.size()] = 0;
2489 Result.Spelling = Spelling;
2490 Result.MustFreeString = 1;
2491 } else {
2492 Result.Spelling = String.data();
2493 Result.MustFreeString = 0;
2494 }
2495 return Result;
2496}
2497}}
2498
Ted Kremenek04bb7162010-01-22 22:44:15 +00002499//===----------------------------------------------------------------------===//
2500// Misc. utility functions.
2501//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002502
Ted Kremenek04bb7162010-01-22 22:44:15 +00002503extern "C" {
2504
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002505CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002506 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002507}
2508
2509} // end: extern "C"