blob: 9171c9ee842f8e67ecccede0b4262abd286c7274 [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) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000161 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000162 // location accordingly.
163 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000164 SourceLocation EndLoc = R.getEnd();
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000165 if (!EndLoc.isInvalid() && EndLoc.isFileID()) {
166 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000167 EndLoc = EndLoc.getFileLocWithOffset(Length);
168 }
169
170 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
171 R.getBegin().getRawEncoding(),
172 EndLoc.getRawEncoding() };
173 return Result;
174}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000175
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000176//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000177// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000178//===----------------------------------------------------------------------===//
179
Steve Naroff89922f82009-08-31 00:59:03 +0000180namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000181
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000183class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000184 public TypeLocVisitor<CursorVisitor, bool>,
185 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000186{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000187 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000188 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000189
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000190 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000191 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000192
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000193 /// \brief The declaration that serves at the parent of any statement or
194 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000195 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000196
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000197 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000198 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000199
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000200 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000201 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000202
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000203 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
204 // to the visitor. Declarations with a PCH level greater than this value will
205 // be suppressed.
206 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207
208 /// \brief When valid, a source range to which the cursor should restrict
209 /// its search.
210 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000211
Douglas Gregorb1373d02010-01-20 20:59:29 +0000212 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000213 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000214 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000215
216 /// \brief Determine whether this particular source range comes before, comes
217 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000219 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000220 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
221
Steve Naroff89922f82009-08-31 00:59:03 +0000222public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000223 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
224 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000225 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000226 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000227 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000228 {
229 Parent.kind = CXCursor_NoDeclFound;
230 Parent.data[0] = 0;
231 Parent.data[1] = 0;
232 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000233 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000234 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000235
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000236 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000237
238 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
239 getPreprocessedEntities();
240
Douglas Gregorb1373d02010-01-20 20:59:29 +0000241 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000242
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000243 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000244 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000245 bool VisitBlockDecl(BlockDecl *B);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000246 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000247 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
248 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000249 bool VisitTagDecl(TagDecl *D);
250 bool VisitEnumConstantDecl(EnumConstantDecl *D);
251 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
252 bool VisitFunctionDecl(FunctionDecl *ND);
253 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000254 bool VisitVarDecl(VarDecl *);
Ted Kremenek79758f62010-02-18 22:36:18 +0000255 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
256 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
257 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
258 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
259 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
260 bool VisitObjCImplDecl(ObjCImplDecl *D);
261 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
262 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
263 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
264 // etc.
265 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
266 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
267 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000268
269 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000270 // FIXME: QualifiedTypeLoc doesn't provide any location information
271 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000272 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000273 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
274 bool VisitTagTypeLoc(TagTypeLoc TL);
275 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
276 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
277 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
278 bool VisitPointerTypeLoc(PointerTypeLoc TL);
279 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
280 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
281 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
282 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
283 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
284 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000285 // FIXME: Implement for TemplateSpecializationTypeLoc
286 // FIXME: Implement visitors here when the unimplemented TypeLocs get
287 // implemented
288 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
289 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000290
Douglas Gregora59e3902010-01-21 23:27:09 +0000291 // Statement visitors
292 bool VisitStmt(Stmt *S);
293 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000294 // FIXME: LabelStmt label?
295 bool VisitIfStmt(IfStmt *S);
296 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000297 bool VisitWhileStmt(WhileStmt *S);
298 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000299
Douglas Gregor336fd812010-01-23 00:40:08 +0000300 // Expression visitors
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000301 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000302 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000303 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000304 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000305 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000306};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000307
Ted Kremenekab188932010-01-05 19:32:54 +0000308} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000309
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000310RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000311 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
312}
313
Douglas Gregorb1373d02010-01-20 20:59:29 +0000314/// \brief Visit the given cursor and, if requested by the visitor,
315/// its children.
316///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000317/// \param Cursor the cursor to visit.
318///
319/// \param CheckRegionOfInterest if true, then the caller already checked that
320/// this cursor is within the region of interest.
321///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000322/// \returns true if the visitation should be aborted, false if it
323/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000324bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000325 if (clang_isInvalid(Cursor.kind))
326 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000327
Douglas Gregorb1373d02010-01-20 20:59:29 +0000328 if (clang_isDeclaration(Cursor.kind)) {
329 Decl *D = getCursorDecl(Cursor);
330 assert(D && "Invalid declaration cursor");
331 if (D->getPCHLevel() > MaxPCHLevel)
332 return false;
333
334 if (D->isImplicit())
335 return false;
336 }
337
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000338 // If we have a range of interest, and this cursor doesn't intersect with it,
339 // we're done.
340 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000341 SourceRange Range =
342 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
343 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000344 return false;
345 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000346
Douglas Gregorb1373d02010-01-20 20:59:29 +0000347 switch (Visitor(Cursor, Parent, ClientData)) {
348 case CXChildVisit_Break:
349 return true;
350
351 case CXChildVisit_Continue:
352 return false;
353
354 case CXChildVisit_Recurse:
355 return VisitChildren(Cursor);
356 }
357
Douglas Gregorfd643772010-01-25 16:45:46 +0000358 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000359}
360
Douglas Gregor788f5a12010-03-20 00:41:21 +0000361std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
362CursorVisitor::getPreprocessedEntities() {
363 PreprocessingRecord &PPRec
364 = *TU->getPreprocessor().getPreprocessingRecord();
365
366 bool OnlyLocalDecls
367 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
368
369 // There is no region of interest; we have to walk everything.
370 if (RegionOfInterest.isInvalid())
371 return std::make_pair(PPRec.begin(OnlyLocalDecls),
372 PPRec.end(OnlyLocalDecls));
373
374 // Find the file in which the region of interest lands.
375 SourceManager &SM = TU->getSourceManager();
376 std::pair<FileID, unsigned> Begin
377 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
378 std::pair<FileID, unsigned> End
379 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
380
381 // The region of interest spans files; we have to walk everything.
382 if (Begin.first != End.first)
383 return std::make_pair(PPRec.begin(OnlyLocalDecls),
384 PPRec.end(OnlyLocalDecls));
385
386 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
387 = TU->getPreprocessedEntitiesByFile();
388 if (ByFileMap.empty()) {
389 // Build the mapping from files to sets of preprocessed entities.
390 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
391 EEnd = PPRec.end(OnlyLocalDecls);
392 E != EEnd; ++E) {
393 std::pair<FileID, unsigned> P
394 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
395 ByFileMap[P.first].push_back(*E);
396 }
397 }
398
399 return std::make_pair(ByFileMap[Begin.first].begin(),
400 ByFileMap[Begin.first].end());
401}
402
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403/// \brief Visit the children of the given cursor.
404///
405/// \returns true if the visitation should be aborted, false if it
406/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000407bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000408 if (clang_isReference(Cursor.kind)) {
409 // By definition, references have no children.
410 return false;
411 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000412
413 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000414 // done.
415 class SetParentRAII {
416 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000417 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000418 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000419
Douglas Gregorb1373d02010-01-20 20:59:29 +0000420 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000421 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000422 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000423 {
424 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000425 if (clang_isDeclaration(Parent.kind))
426 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000427 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000428
Douglas Gregorb1373d02010-01-20 20:59:29 +0000429 ~SetParentRAII() {
430 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000431 if (clang_isDeclaration(Parent.kind))
432 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000433 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000434 } SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000435
Douglas Gregorb1373d02010-01-20 20:59:29 +0000436 if (clang_isDeclaration(Cursor.kind)) {
437 Decl *D = getCursorDecl(Cursor);
438 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000439 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000441
Douglas Gregora59e3902010-01-21 23:27:09 +0000442 if (clang_isStatement(Cursor.kind))
443 return Visit(getCursorStmt(Cursor));
444 if (clang_isExpression(Cursor.kind))
445 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000446
Douglas Gregorb1373d02010-01-20 20:59:29 +0000447 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000448 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000449 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
450 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000451 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
452 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
453 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000454 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000455 return true;
456 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000457 } else if (VisitDeclContext(
458 CXXUnit->getASTContext().getTranslationUnitDecl()))
459 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000460
Douglas Gregor0396f462010-03-19 05:22:59 +0000461 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000462 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000463 // FIXME: Once we have the ability to deserialize a preprocessing record,
464 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000465 PreprocessingRecord::iterator E, EEnd;
466 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000467 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
468 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
469 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000470
Douglas Gregor0396f462010-03-19 05:22:59 +0000471 continue;
472 }
473
474 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
475 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
476 return true;
477
478 continue;
479 }
480 }
481 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000482 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000483 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000484
Douglas Gregorb1373d02010-01-20 20:59:29 +0000485 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000486 return false;
487}
488
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000489bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
490 for (BlockDecl::param_iterator I=B->param_begin(), E=B->param_end(); I!=E;++I)
491 if (Decl *D = *I)
492 if (Visit(D))
493 return true;
494
495 return Visit(MakeCXCursor(B->getBody(), StmtParent, TU));
496}
497
Douglas Gregorb1373d02010-01-20 20:59:29 +0000498bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000499 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000500 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek09dfa372010-02-18 05:46:33 +0000501
Daniel Dunbard52864b2010-02-14 10:02:57 +0000502 CXCursor Cursor = MakeCXCursor(*I, TU);
503
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000504 if (RegionOfInterest.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +0000505 SourceRange Range =
506 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
507 if (Range.isInvalid())
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000508 continue;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000509
510 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000511 case RangeBefore:
512 // This declaration comes before the region of interest; skip it.
513 continue;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000514
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000515 case RangeAfter:
516 // This declaration comes after the region of interest; we're done.
517 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000518
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000519 case RangeOverlap:
520 // This declaration overlaps the region of interest; visit it.
521 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000522 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000523 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000524
Daniel Dunbard52864b2010-02-14 10:02:57 +0000525 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 return true;
527 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000528
Douglas Gregorb1373d02010-01-20 20:59:29 +0000529 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000530}
531
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000532bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
533 llvm_unreachable("Translation units are visited directly by Visit()");
534 return false;
535}
536
537bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
538 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
539 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000540
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000541 return false;
542}
543
544bool CursorVisitor::VisitTagDecl(TagDecl *D) {
545 return VisitDeclContext(D);
546}
547
548bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
549 if (Expr *Init = D->getInitExpr())
550 return Visit(MakeCXCursor(Init, StmtParent, TU));
551 return false;
552}
553
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000554bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
555 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
556 if (Visit(TSInfo->getTypeLoc()))
557 return true;
558
559 return false;
560}
561
Douglas Gregorb1373d02010-01-20 20:59:29 +0000562bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000563 if (VisitDeclaratorDecl(ND))
564 return true;
565
Douglas Gregora59e3902010-01-21 23:27:09 +0000566 if (ND->isThisDeclarationADefinition() &&
567 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
568 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000569
Douglas Gregorb1373d02010-01-20 20:59:29 +0000570 return false;
571}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000572
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000573bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
574 if (VisitDeclaratorDecl(D))
575 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000576
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000577 if (Expr *BitWidth = D->getBitWidth())
578 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000579
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000580 return false;
581}
582
583bool CursorVisitor::VisitVarDecl(VarDecl *D) {
584 if (VisitDeclaratorDecl(D))
585 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000586
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000587 if (Expr *Init = D->getInit())
588 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000589
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000590 return false;
591}
592
593bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000594 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
595 if (Visit(TSInfo->getTypeLoc()))
596 return true;
597
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000598 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599 PEnd = ND->param_end();
600 P != PEnd; ++P) {
601 if (Visit(MakeCXCursor(*P, TU)))
602 return true;
603 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000604
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000605 if (ND->isThisDeclarationADefinition() &&
606 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
607 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000608
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000609 return false;
610}
611
Douglas Gregora59e3902010-01-21 23:27:09 +0000612bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
613 return VisitDeclContext(D);
614}
615
Douglas Gregorb1373d02010-01-20 20:59:29 +0000616bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000617 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
618 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000619 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000620
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000621 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
622 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
623 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000624 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000625 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000626
Douglas Gregora59e3902010-01-21 23:27:09 +0000627 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000628}
629
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000630bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
631 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
632 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
633 E = PID->protocol_end(); I != E; ++I, ++PL)
634 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
635 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000636
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000637 return VisitObjCContainerDecl(PID);
638}
639
Douglas Gregorb1373d02010-01-20 20:59:29 +0000640bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000641 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000642 if (D->getSuperClass() &&
643 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000644 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000645 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000646 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000647
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000648 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
649 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
650 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000651 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000652 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000653
Douglas Gregora59e3902010-01-21 23:27:09 +0000654 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000655}
656
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000657bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
658 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000659}
660
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000661bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000662 // 'ID' could be null when dealing with invalid code.
663 if (ObjCInterfaceDecl *ID = D->getClassInterface())
664 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
665 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000666
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000667 return VisitObjCImplDecl(D);
668}
669
670bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
671#if 0
672 // Issue callbacks for super class.
673 // FIXME: No source location information!
674 if (D->getSuperClass() &&
675 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000676 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000677 TU)))
678 return true;
679#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000680
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000681 return VisitObjCImplDecl(D);
682}
683
684bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
685 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
686 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
687 E = D->protocol_end();
688 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000689 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000690 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000691
692 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000693}
694
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000695bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
696 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
697 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
698 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000699
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000700 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000701}
702
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000703bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
704 ASTContext &Context = TU->getASTContext();
705
706 // Some builtin types (such as Objective-C's "id", "sel", and
707 // "Class") have associated declarations. Create cursors for those.
708 QualType VisitType;
709 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000710 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000711 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000712 case BuiltinType::Char_U:
713 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000714 case BuiltinType::Char16:
715 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000716 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000717 case BuiltinType::UInt:
718 case BuiltinType::ULong:
719 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000720 case BuiltinType::UInt128:
721 case BuiltinType::Char_S:
722 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000723 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000724 case BuiltinType::Short:
725 case BuiltinType::Int:
726 case BuiltinType::Long:
727 case BuiltinType::LongLong:
728 case BuiltinType::Int128:
729 case BuiltinType::Float:
730 case BuiltinType::Double:
731 case BuiltinType::LongDouble:
732 case BuiltinType::NullPtr:
733 case BuiltinType::Overload:
734 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000735 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000736
737 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000738 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000739
Ted Kremenekc4174cc2010-02-18 18:52:18 +0000740 case BuiltinType::ObjCId:
741 VisitType = Context.getObjCIdType();
742 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +0000743
744 case BuiltinType::ObjCClass:
745 VisitType = Context.getObjCClassType();
746 break;
747
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000748 case BuiltinType::ObjCSel:
749 VisitType = Context.getObjCSelType();
750 break;
751 }
752
753 if (!VisitType.isNull()) {
754 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000755 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000756 TU));
757 }
758
759 return false;
760}
761
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000762bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
763 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
764}
765
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000766bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
767 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
768}
769
770bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
771 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
772}
773
774bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
775 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
776 return true;
777
778 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
779 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
780 TU)))
781 return true;
782 }
783
784 return false;
785}
786
787bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
788 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
789 return true;
790
791 if (TL.hasProtocolsAsWritten()) {
792 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000793 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000794 TL.getProtocolLoc(I),
795 TU)))
796 return true;
797 }
798 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000799
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000800 return false;
801}
802
803bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
804 return Visit(TL.getPointeeLoc());
805}
806
807bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
808 return Visit(TL.getPointeeLoc());
809}
810
811bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
812 return Visit(TL.getPointeeLoc());
813}
814
815bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000816 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000817}
818
819bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000820 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000821}
822
823bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
824 if (Visit(TL.getResultLoc()))
825 return true;
826
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000827 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +0000828 if (Decl *D = TL.getArg(I))
829 if (Visit(MakeCXCursor(D, TU)))
830 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000831
832 return false;
833}
834
835bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
836 if (Visit(TL.getElementLoc()))
837 return true;
838
839 if (Expr *Size = TL.getSizeExpr())
840 return Visit(MakeCXCursor(Size, StmtParent, TU));
841
842 return false;
843}
844
Douglas Gregor2332c112010-01-21 20:48:56 +0000845bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
846 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
847}
848
849bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
850 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
851 return Visit(TSInfo->getTypeLoc());
852
853 return false;
854}
855
Douglas Gregora59e3902010-01-21 23:27:09 +0000856bool CursorVisitor::VisitStmt(Stmt *S) {
857 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
858 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000859 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000860 return true;
861 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000862
Douglas Gregora59e3902010-01-21 23:27:09 +0000863 return false;
864}
865
866bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
867 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
868 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000869 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000870 return true;
871 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000872
Douglas Gregora59e3902010-01-21 23:27:09 +0000873 return false;
874}
875
Douglas Gregorf5bab412010-01-22 01:00:11 +0000876bool CursorVisitor::VisitIfStmt(IfStmt *S) {
877 if (VarDecl *Var = S->getConditionVariable()) {
878 if (Visit(MakeCXCursor(Var, TU)))
879 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000880 }
881
Douglas Gregor263b47b2010-01-25 16:12:32 +0000882 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
883 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000884 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
885 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000886 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
887 return true;
888
889 return false;
890}
891
892bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
893 if (VarDecl *Var = S->getConditionVariable()) {
894 if (Visit(MakeCXCursor(Var, TU)))
895 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000896 }
897
Douglas Gregor263b47b2010-01-25 16:12:32 +0000898 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
899 return true;
900 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
901 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000902
Douglas Gregor263b47b2010-01-25 16:12:32 +0000903 return false;
904}
905
906bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
907 if (VarDecl *Var = S->getConditionVariable()) {
908 if (Visit(MakeCXCursor(Var, TU)))
909 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000910 }
911
Douglas Gregor263b47b2010-01-25 16:12:32 +0000912 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
913 return true;
914 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000915 return true;
916
Douglas Gregor263b47b2010-01-25 16:12:32 +0000917 return false;
918}
919
920bool CursorVisitor::VisitForStmt(ForStmt *S) {
921 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
922 return true;
923 if (VarDecl *Var = S->getConditionVariable()) {
924 if (Visit(MakeCXCursor(Var, TU)))
925 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000926 }
927
Douglas Gregor263b47b2010-01-25 16:12:32 +0000928 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
929 return true;
930 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
931 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000932 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
933 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000934
Douglas Gregorf5bab412010-01-22 01:00:11 +0000935 return false;
936}
937
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000938bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
939 return Visit(B->getBlockDecl());
940}
941
Douglas Gregor336fd812010-01-23 00:40:08 +0000942bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
943 if (E->isArgumentType()) {
944 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
945 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000946
Douglas Gregor336fd812010-01-23 00:40:08 +0000947 return false;
948 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000949
Douglas Gregor336fd812010-01-23 00:40:08 +0000950 return VisitExpr(E);
951}
952
953bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
954 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
955 if (Visit(TSInfo->getTypeLoc()))
956 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000957
Douglas Gregor336fd812010-01-23 00:40:08 +0000958 return VisitCastExpr(E);
959}
960
961bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
962 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
963 if (Visit(TSInfo->getTypeLoc()))
964 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000965
Douglas Gregor336fd812010-01-23 00:40:08 +0000966 return VisitExpr(E);
967}
968
Douglas Gregorc2350e52010-03-08 16:40:19 +0000969bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
970 ObjCMessageExpr::ClassInfo CI = E->getClassInfo();
971 if (CI.Decl && Visit(MakeCursorObjCClassRef(CI.Decl, CI.Loc, TU)))
972 return true;
973
974 return VisitExpr(E);
975}
976
Ted Kremenek09dfa372010-02-18 05:46:33 +0000977bool CursorVisitor::VisitAttributes(Decl *D) {
978 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
979 if (Visit(MakeCXCursor(A, D, TU)))
980 return true;
981
982 return false;
983}
984
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000985extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000986CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
987 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000988 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000989 if (excludeDeclarationsFromPCH)
990 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000991 if (displayDiagnostics)
992 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000993 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000994}
995
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000996void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000997 if (CIdx)
998 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000999}
1000
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001001void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001002 if (CIdx) {
1003 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1004 CXXIdx->setUseExternalASTGeneration(value);
1005 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001006}
1007
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001008CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00001009 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001010 if (!CIdx)
1011 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001012
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00001013 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001014
Douglas Gregor28019772010-04-05 23:52:57 +00001015 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1016 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregora88084b2010-02-18 18:08:43 +00001017 CXXIdx->getOnlyLocalDecls(),
1018 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00001019}
1020
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001021CXTranslationUnit
1022clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1023 const char *source_filename,
1024 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001025 const char **command_line_args,
1026 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00001027 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001028 if (!CIdx)
1029 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001030
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001031 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1032
Douglas Gregor5352ac02010-01-28 00:27:43 +00001033 // Configure the diagnostics.
1034 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001035 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1036 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001037
Douglas Gregor4db64a42010-01-23 00:14:00 +00001038 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1039 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00001040 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001041 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001042 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001043 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1044 Buffer));
1045 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001046
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001047 if (!CXXIdx->getUseExternalASTGeneration()) {
1048 llvm::SmallVector<const char *, 16> Args;
1049
1050 // The 'source_filename' argument is optional. If the caller does not
1051 // specify it then it is assumed that the source file is specified
1052 // in the actual argument list.
1053 if (source_filename)
1054 Args.push_back(source_filename);
1055 Args.insert(Args.end(), command_line_args,
1056 command_line_args + num_command_line_args);
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001057 Args.push_back("-Xclang");
1058 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor5352ac02010-01-28 00:27:43 +00001059 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001060
Ted Kremenek29b72842010-01-07 22:49:05 +00001061#ifdef USE_CRASHTRACER
1062 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001063#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001064
Daniel Dunbar94220972009-12-05 02:17:18 +00001065 llvm::OwningPtr<ASTUnit> Unit(
1066 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001067 Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001068 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001069 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001070 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001071 RemappedFiles.size(),
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001072 /*CaptureDiagnostics=*/true));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001073
Daniel Dunbar94220972009-12-05 02:17:18 +00001074 // FIXME: Until we have broader testing, just drop the entire AST if we
1075 // encountered an error.
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001076 if (NumErrors != Diags->getNumErrors()) {
Ted Kremenek34f6a322010-03-05 22:43:29 +00001077 // Make sure to check that 'Unit' is non-NULL.
1078 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregor405634b2010-04-05 18:10:21 +00001079 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1080 DEnd = Unit->stored_diag_end();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001081 D != DEnd; ++D) {
1082 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregor274f1902010-02-22 23:17:23 +00001083 CXString Msg = clang_formatDiagnostic(&Diag,
1084 clang_defaultDiagnosticDisplayOptions());
1085 fprintf(stderr, "%s\n", clang_getCString(Msg));
1086 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001087 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001088#ifdef LLVM_ON_WIN32
1089 // On Windows, force a flush, since there may be multiple copies of
1090 // stderr and stdout in the file system, all with different buffers
1091 // but writing to the same device.
1092 fflush(stderr);
Ted Kremenek83c51842010-03-26 01:34:51 +00001093#endif
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001094 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001095 }
Daniel Dunbar94220972009-12-05 02:17:18 +00001096
1097 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001098 }
1099
Ted Kremenek139ba862009-10-22 00:03:57 +00001100 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001101 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001102
Ted Kremenek139ba862009-10-22 00:03:57 +00001103 // First add the complete path to the 'clang' executable.
1104 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001105 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001106
Ted Kremenek139ba862009-10-22 00:03:57 +00001107 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001108 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001109
Ted Kremenek139ba862009-10-22 00:03:57 +00001110 // The 'source_filename' argument is optional. If the caller does not
1111 // specify it then it is assumed that the source file is specified
1112 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001113 if (source_filename)
1114 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001115
Steve Naroff37b5ac22009-10-15 20:50:09 +00001116 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001117 argv.push_back("-o");
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001118 char astTmpFile[L_tmpnam];
1119 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001120
Douglas Gregor4db64a42010-01-23 00:14:00 +00001121 // Remap any unsaved files to temporary files.
1122 std::vector<llvm::sys::Path> TemporaryFiles;
1123 std::vector<std::string> RemapArgs;
1124 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1125 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001126
Douglas Gregor4db64a42010-01-23 00:14:00 +00001127 // The pointers into the elements of RemapArgs are stable because we
1128 // won't be adding anything to RemapArgs after this point.
1129 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1130 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001131
Ted Kremenek139ba862009-10-22 00:03:57 +00001132 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1133 for (int i = 0; i < num_command_line_args; ++i)
1134 if (const char *arg = command_line_args[i]) {
1135 if (strcmp(arg, "-o") == 0) {
1136 ++i; // Also skip the matching argument.
1137 continue;
1138 }
1139 if (strcmp(arg, "-emit-ast") == 0 ||
1140 strcmp(arg, "-c") == 0 ||
1141 strcmp(arg, "-fsyntax-only") == 0) {
1142 continue;
1143 }
1144
1145 // Keep the argument.
1146 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001147 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001148
Douglas Gregord93256e2010-01-28 06:00:51 +00001149 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +00001150 char tmpFileResults[L_tmpnam];
1151 char *tmpResultsFileName = tmpnam(tmpFileResults);
1152 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +00001153 TemporaryFiles.push_back(DiagnosticsFile);
1154 argv.push_back("-fdiagnostics-binary");
1155
Douglas Gregor94dc8f62010-03-19 16:15:56 +00001156 argv.push_back("-Xclang");
1157 argv.push_back("-detailed-preprocessing-record");
1158
Ted Kremenek139ba862009-10-22 00:03:57 +00001159 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001160 argv.push_back(NULL);
1161
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001162 // Invoke 'clang'.
1163 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1164 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001165 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001166 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1167 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001168 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001169 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001170 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001171
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001172 if (!ErrMsg.empty()) {
1173 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001174 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001175 I != E; ++I) {
1176 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001177 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001178 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001179 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001180
Daniel Dunbar32141c82010-02-23 20:23:45 +00001181 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001182 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001183
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001184 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001185 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001186 RemappedFiles.data(),
Douglas Gregora88084b2010-02-18 18:08:43 +00001187 RemappedFiles.size(),
1188 /*CaptureDiagnostics=*/true);
Douglas Gregora88084b2010-02-18 18:08:43 +00001189 if (ATU) {
1190 LoadSerializedDiagnostics(DiagnosticsFile,
1191 num_unsaved_files, unsaved_files,
1192 ATU->getFileManager(),
1193 ATU->getSourceManager(),
Douglas Gregor405634b2010-04-05 18:10:21 +00001194 ATU->getStoredDiagnostics());
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001195 } else if (CXXIdx->getDisplayDiagnostics()) {
1196 // We failed to load the ASTUnit, but we can still deserialize the
1197 // diagnostics and emit them.
1198 FileManager FileMgr;
Douglas Gregorf715ca12010-03-16 00:06:06 +00001199 Diagnostic Diag;
1200 SourceManager SourceMgr(Diag);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001201 // FIXME: Faked LangOpts!
1202 LangOptions LangOpts;
1203 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1204 LoadSerializedDiagnostics(DiagnosticsFile,
1205 num_unsaved_files, unsaved_files,
1206 FileMgr, SourceMgr, Diags);
1207 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1208 DEnd = Diags.end();
1209 D != DEnd; ++D) {
1210 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregor274f1902010-02-22 23:17:23 +00001211 CXString Msg = clang_formatDiagnostic(&Diag,
1212 clang_defaultDiagnosticDisplayOptions());
1213 fprintf(stderr, "%s\n", clang_getCString(Msg));
1214 clang_disposeString(Msg);
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001215 }
Douglas Gregor274f1902010-02-22 23:17:23 +00001216
1217#ifdef LLVM_ON_WIN32
1218 // On Windows, force a flush, since there may be multiple copies of
1219 // stderr and stdout in the file system, all with different buffers
1220 // but writing to the same device.
1221 fflush(stderr);
1222#endif
Douglas Gregora88084b2010-02-18 18:08:43 +00001223 }
Douglas Gregord93256e2010-01-28 06:00:51 +00001224
Douglas Gregor313e26c2010-02-18 23:35:40 +00001225 if (ATU) {
1226 // Make the translation unit responsible for destroying all temporary files.
1227 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1228 ATU->addTemporaryFile(TemporaryFiles[i]);
1229 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1230 } else {
1231 // Destroy all of the temporary files now; they can't be referenced any
1232 // longer.
1233 llvm::sys::Path(astTmpFile).eraseFromDisk();
1234 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1235 TemporaryFiles[i].eraseFromDisk();
1236 }
1237
Steve Naroffe19944c2009-10-15 22:23:48 +00001238 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001239}
1240
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001241void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001242 if (CTUnit)
1243 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001244}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001245
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001246CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001247 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001248 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001249
Steve Naroff77accc12009-09-03 18:19:54 +00001250 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001251 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001252}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001253
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001254CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001255 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001256 return Result;
1257}
1258
Ted Kremenekfb480492010-01-13 21:46:36 +00001259} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001260
Ted Kremenekfb480492010-01-13 21:46:36 +00001261//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001262// CXSourceLocation and CXSourceRange Operations.
1263//===----------------------------------------------------------------------===//
1264
Douglas Gregorb9790342010-01-22 21:44:22 +00001265extern "C" {
1266CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001267 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001268 return Result;
1269}
1270
1271unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001272 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1273 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1274 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001275}
1276
1277CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1278 CXFile file,
1279 unsigned line,
1280 unsigned column) {
1281 if (!tu)
1282 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001283
Douglas Gregorb9790342010-01-22 21:44:22 +00001284 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1285 SourceLocation SLoc
1286 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001287 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00001288 line, column);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001289
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001290 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001291}
1292
Douglas Gregor5352ac02010-01-28 00:27:43 +00001293CXSourceRange clang_getNullRange() {
1294 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1295 return Result;
1296}
Daniel Dunbard52864b2010-02-14 10:02:57 +00001297
Douglas Gregor5352ac02010-01-28 00:27:43 +00001298CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1299 if (begin.ptr_data[0] != end.ptr_data[0] ||
1300 begin.ptr_data[1] != end.ptr_data[1])
1301 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001302
1303 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001304 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001305 return Result;
1306}
1307
Douglas Gregor46766dc2010-01-26 19:19:08 +00001308void clang_getInstantiationLocation(CXSourceLocation location,
1309 CXFile *file,
1310 unsigned *line,
1311 unsigned *column,
1312 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001313 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1314
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001315 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001316 if (file)
1317 *file = 0;
1318 if (line)
1319 *line = 0;
1320 if (column)
1321 *column = 0;
1322 if (offset)
1323 *offset = 0;
1324 return;
1325 }
1326
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001327 const SourceManager &SM =
1328 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001329 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001330
1331 if (file)
1332 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1333 if (line)
1334 *line = SM.getInstantiationLineNumber(InstLoc);
1335 if (column)
1336 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001337 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001338 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001339}
1340
Douglas Gregor1db19de2010-01-19 21:36:55 +00001341CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001342 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001343 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001344 return Result;
1345}
1346
1347CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001348 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001349 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001350 return Result;
1351}
1352
Douglas Gregorb9790342010-01-22 21:44:22 +00001353} // end: extern "C"
1354
Douglas Gregor1db19de2010-01-19 21:36:55 +00001355//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001356// CXFile Operations.
1357//===----------------------------------------------------------------------===//
1358
1359extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00001360CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001361 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00001362 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001363
Steve Naroff88145032009-10-27 14:35:18 +00001364 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00001365 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00001366}
1367
1368time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001369 if (!SFile)
1370 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001371
Steve Naroff88145032009-10-27 14:35:18 +00001372 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1373 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001374}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001375
Douglas Gregorb9790342010-01-22 21:44:22 +00001376CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1377 if (!tu)
1378 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001379
Douglas Gregorb9790342010-01-22 21:44:22 +00001380 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001381
Douglas Gregorb9790342010-01-22 21:44:22 +00001382 FileManager &FMgr = CXXUnit->getFileManager();
1383 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1384 return const_cast<FileEntry *>(File);
1385}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001386
Ted Kremenekfb480492010-01-13 21:46:36 +00001387} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001388
Ted Kremenekfb480492010-01-13 21:46:36 +00001389//===----------------------------------------------------------------------===//
1390// CXCursor Operations.
1391//===----------------------------------------------------------------------===//
1392
Ted Kremenekfb480492010-01-13 21:46:36 +00001393static Decl *getDeclFromExpr(Stmt *E) {
1394 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1395 return RefExpr->getDecl();
1396 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1397 return ME->getMemberDecl();
1398 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1399 return RE->getDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001400
Ted Kremenekfb480492010-01-13 21:46:36 +00001401 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1402 return getDeclFromExpr(CE->getCallee());
1403 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1404 return getDeclFromExpr(CE->getSubExpr());
1405 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1406 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001407
Ted Kremenekfb480492010-01-13 21:46:36 +00001408 return 0;
1409}
1410
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001411static SourceLocation getLocationFromExpr(Expr *E) {
1412 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1413 return /*FIXME:*/Msg->getLeftLoc();
1414 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1415 return DRE->getLocation();
1416 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1417 return Member->getMemberLoc();
1418 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1419 return Ivar->getLocation();
1420 return E->getLocStart();
1421}
1422
Ted Kremenekfb480492010-01-13 21:46:36 +00001423extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001424
1425unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001426 CXCursorVisitor visitor,
1427 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001428 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001429
1430 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001431
Douglas Gregorb1373d02010-01-20 20:59:29 +00001432 // Set the PCHLevel to filter out unwanted decls if requested.
1433 if (CXXUnit->getOnlyLocalDecls()) {
1434 PCHLevel = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001435
Douglas Gregorb1373d02010-01-20 20:59:29 +00001436 // If the main input was an AST, bump the level.
1437 if (CXXUnit->isMainFileAST())
1438 ++PCHLevel;
1439 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001440
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001441 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001442 return CursorVis.VisitChildren(parent);
1443}
1444
Douglas Gregor78205d42010-01-20 21:45:58 +00001445static CXString getDeclSpelling(Decl *D) {
1446 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1447 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001448 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001449
Douglas Gregor78205d42010-01-20 21:45:58 +00001450 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001451 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001452
Douglas Gregor78205d42010-01-20 21:45:58 +00001453 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1454 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1455 // and returns different names. NamedDecl returns the class name and
1456 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001457 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001458
Douglas Gregor78205d42010-01-20 21:45:58 +00001459 if (ND->getIdentifier())
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001460 return createCXString(ND->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001461
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001462 return createCXString("");
Douglas Gregor78205d42010-01-20 21:45:58 +00001463}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001464
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001465CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001466 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001467 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001468
Steve Narofff334b4e2009-09-02 18:26:48 +00001469 if (clang_isReference(C.kind)) {
1470 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001471 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001472 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001473 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001474 }
1475 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001476 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001477 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001478 }
1479 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001480 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001481 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001482 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001483 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001484 case CXCursor_TypeRef: {
1485 TypeDecl *Type = getCursorTypeRef(C).first;
1486 assert(Type && "Missing type decl");
1487
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001488 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1489 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001490 }
1491
Daniel Dunbaracca7252009-11-30 20:42:49 +00001492 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001493 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001494 }
1495 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001496
1497 if (clang_isExpression(C.kind)) {
1498 Decl *D = getDeclFromExpr(getCursorExpr(C));
1499 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001500 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001501 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00001502 }
1503
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001504 if (C.kind == CXCursor_MacroInstantiation)
1505 return createCXString(getCursorMacroInstantiation(C)->getName()
1506 ->getNameStart());
1507
Douglas Gregor572feb22010-03-18 18:04:21 +00001508 if (C.kind == CXCursor_MacroDefinition)
1509 return createCXString(getCursorMacroDefinition(C)->getName()
1510 ->getNameStart());
1511
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001512 if (clang_isDeclaration(C.kind))
1513 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001514
Ted Kremenekee4db4f2010-02-17 00:41:08 +00001515 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001516}
1517
Ted Kremeneke68fff62010-02-17 00:41:32 +00001518CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001519 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001520 case CXCursor_FunctionDecl:
1521 return createCXString("FunctionDecl");
1522 case CXCursor_TypedefDecl:
1523 return createCXString("TypedefDecl");
1524 case CXCursor_EnumDecl:
1525 return createCXString("EnumDecl");
1526 case CXCursor_EnumConstantDecl:
1527 return createCXString("EnumConstantDecl");
1528 case CXCursor_StructDecl:
1529 return createCXString("StructDecl");
1530 case CXCursor_UnionDecl:
1531 return createCXString("UnionDecl");
1532 case CXCursor_ClassDecl:
1533 return createCXString("ClassDecl");
1534 case CXCursor_FieldDecl:
1535 return createCXString("FieldDecl");
1536 case CXCursor_VarDecl:
1537 return createCXString("VarDecl");
1538 case CXCursor_ParmDecl:
1539 return createCXString("ParmDecl");
1540 case CXCursor_ObjCInterfaceDecl:
1541 return createCXString("ObjCInterfaceDecl");
1542 case CXCursor_ObjCCategoryDecl:
1543 return createCXString("ObjCCategoryDecl");
1544 case CXCursor_ObjCProtocolDecl:
1545 return createCXString("ObjCProtocolDecl");
1546 case CXCursor_ObjCPropertyDecl:
1547 return createCXString("ObjCPropertyDecl");
1548 case CXCursor_ObjCIvarDecl:
1549 return createCXString("ObjCIvarDecl");
1550 case CXCursor_ObjCInstanceMethodDecl:
1551 return createCXString("ObjCInstanceMethodDecl");
1552 case CXCursor_ObjCClassMethodDecl:
1553 return createCXString("ObjCClassMethodDecl");
1554 case CXCursor_ObjCImplementationDecl:
1555 return createCXString("ObjCImplementationDecl");
1556 case CXCursor_ObjCCategoryImplDecl:
1557 return createCXString("ObjCCategoryImplDecl");
1558 case CXCursor_UnexposedDecl:
1559 return createCXString("UnexposedDecl");
1560 case CXCursor_ObjCSuperClassRef:
1561 return createCXString("ObjCSuperClassRef");
1562 case CXCursor_ObjCProtocolRef:
1563 return createCXString("ObjCProtocolRef");
1564 case CXCursor_ObjCClassRef:
1565 return createCXString("ObjCClassRef");
1566 case CXCursor_TypeRef:
1567 return createCXString("TypeRef");
1568 case CXCursor_UnexposedExpr:
1569 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001570 case CXCursor_BlockExpr:
1571 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001572 case CXCursor_DeclRefExpr:
1573 return createCXString("DeclRefExpr");
1574 case CXCursor_MemberRefExpr:
1575 return createCXString("MemberRefExpr");
1576 case CXCursor_CallExpr:
1577 return createCXString("CallExpr");
1578 case CXCursor_ObjCMessageExpr:
1579 return createCXString("ObjCMessageExpr");
1580 case CXCursor_UnexposedStmt:
1581 return createCXString("UnexposedStmt");
1582 case CXCursor_InvalidFile:
1583 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00001584 case CXCursor_InvalidCode:
1585 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001586 case CXCursor_NoDeclFound:
1587 return createCXString("NoDeclFound");
1588 case CXCursor_NotImplemented:
1589 return createCXString("NotImplemented");
1590 case CXCursor_TranslationUnit:
1591 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00001592 case CXCursor_UnexposedAttr:
1593 return createCXString("UnexposedAttr");
1594 case CXCursor_IBActionAttr:
1595 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001596 case CXCursor_IBOutletAttr:
1597 return createCXString("attribute(iboutlet)");
1598 case CXCursor_PreprocessingDirective:
1599 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00001600 case CXCursor_MacroDefinition:
1601 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00001602 case CXCursor_MacroInstantiation:
1603 return createCXString("macro instantiation");
Steve Naroff89922f82009-08-31 00:59:03 +00001604 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001605
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001606 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001607 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00001608}
Steve Naroff89922f82009-08-31 00:59:03 +00001609
Ted Kremeneke68fff62010-02-17 00:41:32 +00001610enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1611 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001612 CXClientData client_data) {
1613 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1614 *BestCursor = cursor;
1615 return CXChildVisit_Recurse;
1616}
Ted Kremeneke68fff62010-02-17 00:41:32 +00001617
Douglas Gregorb9790342010-01-22 21:44:22 +00001618CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1619 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001620 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00001621
Douglas Gregorb9790342010-01-22 21:44:22 +00001622 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1623
Douglas Gregorbdf60622010-03-05 21:16:25 +00001624 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1625
Ted Kremeneka297de22010-01-25 22:34:44 +00001626 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001627 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1628 if (SLoc.isValid()) {
Daniel Dunbard52864b2010-02-14 10:02:57 +00001629 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremeneke68fff62010-02-17 00:41:32 +00001630
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001631 // FIXME: Would be great to have a "hint" cursor, then walk from that
1632 // hint cursor upward until we find a cursor whose source range encloses
1633 // the region of interest, rather than starting from the translation unit.
1634 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001635 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001636 Decl::MaxPCHLevel, RegionOfInterest);
1637 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001638 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001639 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001640}
1641
Ted Kremenek73885552009-11-17 19:28:59 +00001642CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001643 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001644}
1645
1646unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001647 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001648}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001649
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001650unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001651 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1652}
1653
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001654unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001655 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1656}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001657
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001658unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001659 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1660}
1661
Douglas Gregor97b98722010-01-19 23:20:36 +00001662unsigned clang_isExpression(enum CXCursorKind K) {
1663 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1664}
1665
1666unsigned clang_isStatement(enum CXCursorKind K) {
1667 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1668}
1669
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001670unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1671 return K == CXCursor_TranslationUnit;
1672}
1673
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001674unsigned clang_isPreprocessing(enum CXCursorKind K) {
1675 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1676}
1677
Ted Kremenekad6eff62010-03-08 21:17:29 +00001678unsigned clang_isUnexposed(enum CXCursorKind K) {
1679 switch (K) {
1680 case CXCursor_UnexposedDecl:
1681 case CXCursor_UnexposedExpr:
1682 case CXCursor_UnexposedStmt:
1683 case CXCursor_UnexposedAttr:
1684 return true;
1685 default:
1686 return false;
1687 }
1688}
1689
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001690CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001691 return C.kind;
1692}
1693
Douglas Gregor98258af2010-01-18 22:46:11 +00001694CXSourceLocation clang_getCursorLocation(CXCursor C) {
1695 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001696 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001697 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001698 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1699 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001700 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001701 }
1702
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001703 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001704 std::pair<ObjCProtocolDecl *, SourceLocation> P
1705 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001706 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001707 }
1708
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001709 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001710 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1711 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001712 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001713 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001714
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001715 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001716 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001717 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001718 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001719
Douglas Gregorf46034a2010-01-18 23:41:10 +00001720 default:
1721 // FIXME: Need a way to enumerate all non-reference cases.
1722 llvm_unreachable("Missed a reference kind");
1723 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001724 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001725
1726 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001727 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001728 getLocationFromExpr(getCursorExpr(C)));
1729
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001730 if (C.kind == CXCursor_PreprocessingDirective) {
1731 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1732 return cxloc::translateSourceLocation(getCursorContext(C), L);
1733 }
Douglas Gregor48072312010-03-18 15:23:44 +00001734
1735 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001736 SourceLocation L
1737 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00001738 return cxloc::translateSourceLocation(getCursorContext(C), L);
1739 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001740
1741 if (C.kind == CXCursor_MacroDefinition) {
1742 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1743 return cxloc::translateSourceLocation(getCursorContext(C), L);
1744 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001745
Douglas Gregor5352ac02010-01-28 00:27:43 +00001746 if (!getCursorDecl(C))
1747 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001748
Douglas Gregorf46034a2010-01-18 23:41:10 +00001749 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001750 SourceLocation Loc = D->getLocation();
1751 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1752 Loc = Class->getClassLoc();
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001753 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001754}
Douglas Gregora7bde202010-01-19 00:34:46 +00001755
1756CXSourceRange clang_getCursorExtent(CXCursor C) {
1757 if (clang_isReference(C.kind)) {
1758 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001759 case CXCursor_ObjCSuperClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001760 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1761 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001762 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001763 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001764
1765 case CXCursor_ObjCProtocolRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001766 std::pair<ObjCProtocolDecl *, SourceLocation> P
1767 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001768 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001769 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001770
1771 case CXCursor_ObjCClassRef: {
Douglas Gregora7bde202010-01-19 00:34:46 +00001772 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1773 = getCursorObjCClassRef(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001774
Ted Kremeneka297de22010-01-25 22:34:44 +00001775 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001776 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001777
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001778 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001779 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001780 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001781 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001782
Douglas Gregora7bde202010-01-19 00:34:46 +00001783 default:
1784 // FIXME: Need a way to enumerate all non-reference cases.
1785 llvm_unreachable("Missed a reference kind");
1786 }
1787 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001788
1789 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001790 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001791 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001792
1793 if (clang_isStatement(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001794 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001795 getCursorStmt(C)->getSourceRange());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001796
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001797 if (C.kind == CXCursor_PreprocessingDirective) {
1798 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1799 return cxloc::translateSourceRange(getCursorContext(C), R);
1800 }
Douglas Gregor48072312010-03-18 15:23:44 +00001801
1802 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00001803 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor48072312010-03-18 15:23:44 +00001804 return cxloc::translateSourceRange(getCursorContext(C), R);
1805 }
Douglas Gregor572feb22010-03-18 18:04:21 +00001806
1807 if (C.kind == CXCursor_MacroDefinition) {
1808 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1809 return cxloc::translateSourceRange(getCursorContext(C), R);
1810 }
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00001811
Douglas Gregor5352ac02010-01-28 00:27:43 +00001812 if (!getCursorDecl(C))
1813 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001814
Douglas Gregora7bde202010-01-19 00:34:46 +00001815 Decl *D = getCursorDecl(C);
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00001816 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001817}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001818
1819CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001820 if (clang_isInvalid(C.kind))
1821 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001822
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001823 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001824 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001825 return C;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001826
Douglas Gregor97b98722010-01-19 23:20:36 +00001827 if (clang_isExpression(C.kind)) {
1828 Decl *D = getDeclFromExpr(getCursorExpr(C));
1829 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001830 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001831 return clang_getNullCursor();
1832 }
1833
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001834 if (C.kind == CXCursor_MacroInstantiation) {
1835 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1836 return MakeMacroDefinitionCursor(Def, CXXUnit);
1837 }
1838
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001839 if (!clang_isReference(C.kind))
1840 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001841
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001842 switch (C.kind) {
1843 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001844 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001845
1846 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001847 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001848
1849 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001850 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001851
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001852 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001853 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001854
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001855 default:
1856 // We would prefer to enumerate all non-reference cursor kinds here.
1857 llvm_unreachable("Unhandled reference cursor kind");
1858 break;
1859 }
1860 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001861
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001862 return clang_getNullCursor();
1863}
1864
Douglas Gregorb6998662010-01-19 19:34:47 +00001865CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001866 if (clang_isInvalid(C.kind))
1867 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001868
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001869 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001870
Douglas Gregorb6998662010-01-19 19:34:47 +00001871 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001872 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001873 C = clang_getCursorReferenced(C);
1874 WasReference = true;
1875 }
1876
Douglas Gregorbf7efa22010-03-18 18:23:03 +00001877 if (C.kind == CXCursor_MacroInstantiation)
1878 return clang_getCursorReferenced(C);
1879
Douglas Gregorb6998662010-01-19 19:34:47 +00001880 if (!clang_isDeclaration(C.kind))
1881 return clang_getNullCursor();
1882
1883 Decl *D = getCursorDecl(C);
1884 if (!D)
1885 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001886
Douglas Gregorb6998662010-01-19 19:34:47 +00001887 switch (D->getKind()) {
1888 // Declaration kinds that don't really separate the notions of
1889 // declaration and definition.
1890 case Decl::Namespace:
1891 case Decl::Typedef:
1892 case Decl::TemplateTypeParm:
1893 case Decl::EnumConstant:
1894 case Decl::Field:
1895 case Decl::ObjCIvar:
1896 case Decl::ObjCAtDefsField:
1897 case Decl::ImplicitParam:
1898 case Decl::ParmVar:
1899 case Decl::NonTypeTemplateParm:
1900 case Decl::TemplateTemplateParm:
1901 case Decl::ObjCCategoryImpl:
1902 case Decl::ObjCImplementation:
1903 case Decl::LinkageSpec:
1904 case Decl::ObjCPropertyImpl:
1905 case Decl::FileScopeAsm:
1906 case Decl::StaticAssert:
1907 case Decl::Block:
1908 return C;
1909
1910 // Declaration kinds that don't make any sense here, but are
1911 // nonetheless harmless.
1912 case Decl::TranslationUnit:
1913 case Decl::Template:
1914 case Decl::ObjCContainer:
1915 break;
1916
1917 // Declaration kinds for which the definition is not resolvable.
1918 case Decl::UnresolvedUsingTypename:
1919 case Decl::UnresolvedUsingValue:
1920 break;
1921
1922 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001923 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1924 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001925
1926 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001927 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001928
1929 case Decl::Enum:
1930 case Decl::Record:
1931 case Decl::CXXRecord:
1932 case Decl::ClassTemplateSpecialization:
1933 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001934 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001935 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001936 return clang_getNullCursor();
1937
1938 case Decl::Function:
1939 case Decl::CXXMethod:
1940 case Decl::CXXConstructor:
1941 case Decl::CXXDestructor:
1942 case Decl::CXXConversion: {
1943 const FunctionDecl *Def = 0;
1944 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001945 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001946 return clang_getNullCursor();
1947 }
1948
1949 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001950 // Ask the variable if it has a definition.
1951 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1952 return MakeCXCursor(Def, CXXUnit);
1953 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001954 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001955
Douglas Gregorb6998662010-01-19 19:34:47 +00001956 case Decl::FunctionTemplate: {
1957 const FunctionDecl *Def = 0;
1958 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001959 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001960 return clang_getNullCursor();
1961 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001962
Douglas Gregorb6998662010-01-19 19:34:47 +00001963 case Decl::ClassTemplate: {
1964 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001965 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001966 return MakeCXCursor(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001967 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001968 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001969 return clang_getNullCursor();
1970 }
1971
1972 case Decl::Using: {
1973 UsingDecl *Using = cast<UsingDecl>(D);
1974 CXCursor Def = clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001975 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1976 SEnd = Using->shadow_end();
Douglas Gregorb6998662010-01-19 19:34:47 +00001977 S != SEnd; ++S) {
1978 if (Def != clang_getNullCursor()) {
1979 // FIXME: We have no way to return multiple results.
1980 return clang_getNullCursor();
1981 }
1982
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001983 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001984 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001985 }
1986
1987 return Def;
1988 }
1989
1990 case Decl::UsingShadow:
1991 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001992 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001993 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001994
1995 case Decl::ObjCMethod: {
1996 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1997 if (Method->isThisDeclarationADefinition())
1998 return C;
1999
2000 // Dig out the method definition in the associated
2001 // @implementation, if we have it.
2002 // FIXME: The ASTs should make finding the definition easier.
2003 if (ObjCInterfaceDecl *Class
2004 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2005 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2006 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2007 Method->isInstanceMethod()))
2008 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002009 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002010
2011 return clang_getNullCursor();
2012 }
2013
2014 case Decl::ObjCCategory:
2015 if (ObjCCategoryImplDecl *Impl
2016 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002017 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002018 return clang_getNullCursor();
2019
2020 case Decl::ObjCProtocol:
2021 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2022 return C;
2023 return clang_getNullCursor();
2024
2025 case Decl::ObjCInterface:
2026 // There are two notions of a "definition" for an Objective-C
2027 // class: the interface and its implementation. When we resolved a
2028 // reference to an Objective-C class, produce the @interface as
2029 // the definition; when we were provided with the interface,
2030 // produce the @implementation as the definition.
2031 if (WasReference) {
2032 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2033 return C;
2034 } else if (ObjCImplementationDecl *Impl
2035 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002036 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002037 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002038
Douglas Gregorb6998662010-01-19 19:34:47 +00002039 case Decl::ObjCProperty:
2040 // FIXME: We don't really know where to find the
2041 // ObjCPropertyImplDecls that implement this property.
2042 return clang_getNullCursor();
2043
2044 case Decl::ObjCCompatibleAlias:
2045 if (ObjCInterfaceDecl *Class
2046 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2047 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002048 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002049
Douglas Gregorb6998662010-01-19 19:34:47 +00002050 return clang_getNullCursor();
2051
2052 case Decl::ObjCForwardProtocol: {
2053 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2054 if (Forward->protocol_size() == 1)
2055 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002056 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002057 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002058
2059 // FIXME: Cannot return multiple definitions.
2060 return clang_getNullCursor();
2061 }
2062
2063 case Decl::ObjCClass: {
2064 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2065 if (Class->size() == 1) {
2066 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2067 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002068 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00002069 return clang_getNullCursor();
2070 }
2071
2072 // FIXME: Cannot return multiple definitions.
2073 return clang_getNullCursor();
2074 }
2075
2076 case Decl::Friend:
2077 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002078 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002079 return clang_getNullCursor();
2080
2081 case Decl::FriendTemplate:
2082 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002083 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00002084 return clang_getNullCursor();
2085 }
2086
2087 return clang_getNullCursor();
2088}
2089
2090unsigned clang_isCursorDefinition(CXCursor C) {
2091 if (!clang_isDeclaration(C.kind))
2092 return 0;
2093
2094 return clang_getCursorDefinition(C) == C;
2095}
2096
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002097void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00002098 const char **startBuf,
2099 const char **endBuf,
2100 unsigned *startLine,
2101 unsigned *startColumn,
2102 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002103 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00002104 assert(getCursorDecl(C) && "CXCursor has null decl");
2105 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00002106 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2107 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002108
Steve Naroff4ade6d62009-09-23 17:52:52 +00002109 SourceManager &SM = FD->getASTContext().getSourceManager();
2110 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2111 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2112 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2113 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2114 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2115 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2116}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002117
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002118void clang_enableStackTraces(void) {
2119 llvm::sys::PrintStackTraceOnErrorSignal();
2120}
2121
Ted Kremenekfb480492010-01-13 21:46:36 +00002122} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00002123
Ted Kremenekfb480492010-01-13 21:46:36 +00002124//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002125// Token-based Operations.
2126//===----------------------------------------------------------------------===//
2127
2128/* CXToken layout:
2129 * int_data[0]: a CXTokenKind
2130 * int_data[1]: starting token location
2131 * int_data[2]: token length
2132 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002133 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002134 * otherwise unused.
2135 */
2136extern "C" {
2137
2138CXTokenKind clang_getTokenKind(CXToken CXTok) {
2139 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2140}
2141
2142CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2143 switch (clang_getTokenKind(CXTok)) {
2144 case CXToken_Identifier:
2145 case CXToken_Keyword:
2146 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002147 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2148 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002149
2150 case CXToken_Literal: {
2151 // We have stashed the starting pointer in the ptr_data field. Use it.
2152 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002153 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002154 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002155
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002156 case CXToken_Punctuation:
2157 case CXToken_Comment:
2158 break;
2159 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002160
2161 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002162 // deconstructing the source location.
2163 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2164 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002165 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002166
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002167 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2168 std::pair<FileID, unsigned> LocInfo
2169 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00002170 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002171 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002172 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2173 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002174 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002175
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002176 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002177}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002178
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002179CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2180 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2181 if (!CXXUnit)
2182 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002183
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002184 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2185 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2186}
2187
2188CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2189 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00002190 if (!CXXUnit)
2191 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002192
2193 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002194 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2195}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002196
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002197void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2198 CXToken **Tokens, unsigned *NumTokens) {
2199 if (Tokens)
2200 *Tokens = 0;
2201 if (NumTokens)
2202 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002203
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002204 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2205 if (!CXXUnit || !Tokens || !NumTokens)
2206 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002207
Douglas Gregorbdf60622010-03-05 21:16:25 +00002208 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2209
Daniel Dunbar85b988f2010-02-14 08:31:57 +00002210 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002211 if (R.isInvalid())
2212 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002213
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002214 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2215 std::pair<FileID, unsigned> BeginLocInfo
2216 = SourceMgr.getDecomposedLoc(R.getBegin());
2217 std::pair<FileID, unsigned> EndLocInfo
2218 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002219
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002220 // Cannot tokenize across files.
2221 if (BeginLocInfo.first != EndLocInfo.first)
2222 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002223
2224 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002225 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002226 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00002227 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00002228 if (Invalid)
2229 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00002230
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002231 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2232 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002233 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002234 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002235
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002236 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002237 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002238 llvm::SmallVector<CXToken, 32> CXTokens;
2239 Token Tok;
2240 do {
2241 // Lex the next token
2242 Lex.LexFromRawLexer(Tok);
2243 if (Tok.is(tok::eof))
2244 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002245
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002246 // Initialize the CXToken.
2247 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002248
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002249 // - Common fields
2250 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2251 CXTok.int_data[2] = Tok.getLength();
2252 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002253
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002254 // - Kind-specific fields
2255 if (Tok.isLiteral()) {
2256 CXTok.int_data[0] = CXToken_Literal;
2257 CXTok.ptr_data = (void *)Tok.getLiteralData();
2258 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00002259 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002260 std::pair<FileID, unsigned> LocInfo
2261 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00002262 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002263 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00002264 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2265 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00002266 return;
2267
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00002268 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002269 IdentifierInfo *II
2270 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2271 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2272 CXToken_Identifier
2273 : CXToken_Keyword;
2274 CXTok.ptr_data = II;
2275 } else if (Tok.is(tok::comment)) {
2276 CXTok.int_data[0] = CXToken_Comment;
2277 CXTok.ptr_data = 0;
2278 } else {
2279 CXTok.int_data[0] = CXToken_Punctuation;
2280 CXTok.ptr_data = 0;
2281 }
2282 CXTokens.push_back(CXTok);
2283 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002284
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002285 if (CXTokens.empty())
2286 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002287
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002288 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2289 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2290 *NumTokens = CXTokens.size();
2291}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002292
2293typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2294
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002295enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2296 CXCursor parent,
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002297 CXClientData client_data) {
2298 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2299
2300 // We only annotate the locations of declarations, simple
2301 // references, and expressions which directly reference something.
2302 CXCursorKind Kind = clang_getCursorKind(cursor);
2303 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2304 // Okay: We can annotate the location of this declaration with the
2305 // declaration or reference
2306 } else if (clang_isExpression(cursor.kind)) {
2307 if (Kind != CXCursor_DeclRefExpr &&
2308 Kind != CXCursor_MemberRefExpr &&
2309 Kind != CXCursor_ObjCMessageExpr)
2310 return CXChildVisit_Recurse;
2311
2312 CXCursor Referenced = clang_getCursorReferenced(cursor);
2313 if (Referenced == cursor || Referenced == clang_getNullCursor())
2314 return CXChildVisit_Recurse;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002315
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002316 // Okay: we can annotate the location of this expression
Douglas Gregor0396f462010-03-19 05:22:59 +00002317 } else if (clang_isPreprocessing(cursor.kind)) {
2318 // We can always annotate a preprocessing directive/macro instantiation.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002319 } else {
2320 // Nothing to annotate
2321 return CXChildVisit_Recurse;
2322 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002323
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002324 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2325 (*Data)[Loc.int_data] = cursor;
2326 return CXChildVisit_Recurse;
2327}
2328
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002329void clang_annotateTokens(CXTranslationUnit TU,
2330 CXToken *Tokens, unsigned NumTokens,
2331 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002332 if (NumTokens == 0)
2333 return;
2334
2335 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002336 for (unsigned I = 0; I != NumTokens; ++I)
2337 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002338
2339 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2340 if (!CXXUnit || !Tokens)
2341 return;
2342
Douglas Gregorbdf60622010-03-05 21:16:25 +00002343 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2344
Douglas Gregor0396f462010-03-19 05:22:59 +00002345 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002346 SourceRange RegionOfInterest;
2347 RegionOfInterest.setBegin(
2348 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2349 SourceLocation End
Douglas Gregor09d9fa12010-04-05 16:10:30 +00002350 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
Douglas Gregor0396f462010-03-19 05:22:59 +00002351 Tokens[NumTokens - 1]));
Daniel Dunbard52864b2010-02-14 10:02:57 +00002352 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Douglas Gregor2507fa82010-03-19 00:18:31 +00002353
Douglas Gregor0396f462010-03-19 05:22:59 +00002354 // A mapping from the source locations found when re-lexing or traversing the
2355 // region of interest to the corresponding cursors.
2356 AnnotateTokensData Annotated;
2357
2358 // Relex the tokens within the source range to look for preprocessing
2359 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002360 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2361 std::pair<FileID, unsigned> BeginLocInfo
2362 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2363 std::pair<FileID, unsigned> EndLocInfo
2364 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
2365
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002366 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00002367 bool Invalid = false;
2368 if (BeginLocInfo.first == EndLocInfo.first &&
2369 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2370 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002371 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2372 CXXUnit->getASTContext().getLangOptions(),
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002373 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
2374 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002375 Lex.SetCommentRetentionState(true);
2376
2377 // Lex tokens in raw mode until we hit the end of the range, to avoid
2378 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00002379 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002380 Token Tok;
2381 Lex.LexFromRawLexer(Tok);
2382
2383 reprocess:
2384 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2385 // We have found a preprocessing directive. Gobble it up so that we
2386 // don't see it while preprocessing these tokens later, but keep track of
2387 // all of the token locations inside this preprocessing directive so that
2388 // we can annotate them appropriately.
2389 //
2390 // FIXME: Some simple tests here could identify macro definitions and
2391 // #undefs, to provide specific cursor kinds for those.
2392 std::vector<SourceLocation> Locations;
2393 do {
2394 Locations.push_back(Tok.getLocation());
2395 Lex.LexFromRawLexer(Tok);
2396 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
2397
2398 using namespace cxcursor;
2399 CXCursor Cursor
2400 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2401 Locations.back()),
2402 CXXUnit);
2403 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2404 Annotated[Locations[I].getRawEncoding()] = Cursor;
2405 }
2406
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002407 if (Tok.isAtStartOfLine())
2408 goto reprocess;
2409
2410 continue;
2411 }
2412
Douglas Gregor48072312010-03-18 15:23:44 +00002413 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002414 break;
2415 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002416 }
Douglas Gregor0396f462010-03-19 05:22:59 +00002417
2418 // Annotate all of the source locations in the region of interest that map to
2419 // a specific cursor.
2420 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2421 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2422 Decl::MaxPCHLevel, RegionOfInterest);
2423 AnnotateVis.VisitChildren(Parent);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002424
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002425 for (unsigned I = 0; I != NumTokens; ++I) {
2426 // Determine whether we saw a cursor at this token's location.
2427 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2428 if (Pos == Annotated.end())
2429 continue;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002430
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002431 Cursors[I] = Pos->second;
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002432 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002433}
2434
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002435void clang_disposeTokens(CXTranslationUnit TU,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002436 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002437 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002438}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002439
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002440} // end: extern "C"
2441
2442//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00002443// Operations for querying linkage of a cursor.
2444//===----------------------------------------------------------------------===//
2445
2446extern "C" {
2447CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00002448 if (!clang_isDeclaration(cursor.kind))
2449 return CXLinkage_Invalid;
2450
Ted Kremenek16b42592010-03-03 06:36:57 +00002451 Decl *D = cxcursor::getCursorDecl(cursor);
2452 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2453 switch (ND->getLinkage()) {
2454 case NoLinkage: return CXLinkage_NoLinkage;
2455 case InternalLinkage: return CXLinkage_Internal;
2456 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2457 case ExternalLinkage: return CXLinkage_External;
2458 };
2459
2460 return CXLinkage_Invalid;
2461}
2462} // end: extern "C"
2463
2464//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002465// CXString Operations.
2466//===----------------------------------------------------------------------===//
2467
2468extern "C" {
2469const char *clang_getCString(CXString string) {
2470 return string.Spelling;
2471}
2472
2473void clang_disposeString(CXString string) {
2474 if (string.MustFreeString && string.Spelling)
2475 free((void*)string.Spelling);
2476}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002477
Ted Kremenekfb480492010-01-13 21:46:36 +00002478} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002479
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002480namespace clang { namespace cxstring {
2481CXString createCXString(const char *String, bool DupString){
2482 CXString Str;
2483 if (DupString) {
2484 Str.Spelling = strdup(String);
2485 Str.MustFreeString = 1;
2486 } else {
2487 Str.Spelling = String;
2488 Str.MustFreeString = 0;
2489 }
2490 return Str;
2491}
2492
2493CXString createCXString(llvm::StringRef String, bool DupString) {
2494 CXString Result;
2495 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2496 char *Spelling = (char *)malloc(String.size() + 1);
2497 memmove(Spelling, String.data(), String.size());
2498 Spelling[String.size()] = 0;
2499 Result.Spelling = Spelling;
2500 Result.MustFreeString = 1;
2501 } else {
2502 Result.Spelling = String.data();
2503 Result.MustFreeString = 0;
2504 }
2505 return Result;
2506}
2507}}
2508
Ted Kremenek04bb7162010-01-22 22:44:15 +00002509//===----------------------------------------------------------------------===//
2510// Misc. utility functions.
2511//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002512
Ted Kremenek04bb7162010-01-22 22:44:15 +00002513extern "C" {
2514
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002515CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002516 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00002517}
2518
2519} // end: extern "C"