blob: 5f8e25353d74c4a792773a2f0304cb6eac8bc166 [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"
Ted Kremenekfc062212009-10-19 21:44:57 +000030
Ted Kremenekdb3d0da2010-01-05 20:55:39 +000031// Needed to define L_TMPNAM on some systems.
32#include <cstdio>
33
Steve Naroff50398192009-08-28 15:28:48 +000034using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000035using namespace clang::cxcursor;
Steve Naroff50398192009-08-28 15:28:48 +000036using namespace idx;
37
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000038//===----------------------------------------------------------------------===//
39// Crash Reporting.
40//===----------------------------------------------------------------------===//
41
42#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000043#ifndef NDEBUG
44#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000045#include "clang/Analysis/Support/SaveAndRestore.h"
46// Integrate with crash reporter.
47extern "C" const char *__crashreporter_info__;
Ted Kremenek29b72842010-01-07 22:49:05 +000048#define NUM_CRASH_STRINGS 16
49static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000050static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000051static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
52static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
53
54static unsigned SetCrashTracerInfo(const char *str,
55 llvm::SmallString<1024> &AggStr) {
56
Ted Kremenek254ba7c2010-01-07 23:13:53 +000057 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000058 while (crashtracer_strings[slot]) {
59 if (++slot == NUM_CRASH_STRINGS)
60 slot = 0;
61 }
62 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000063 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000064
65 // We need to create an aggregate string because multiple threads
66 // may be in this method at one time. The crash reporter string
67 // will attempt to overapproximate the set of in-flight invocations
68 // of this function. Race conditions can still cause this goal
69 // to not be achieved.
70 {
71 llvm::raw_svector_ostream Out(AggStr);
72 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
73 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
74 }
75 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
76 return slot;
77}
78
79static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000080 unsigned max_slot = 0;
81 unsigned max_value = 0;
82
83 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
84
85 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
86 if (agg_crashtracer_strings[i] &&
87 crashtracer_counter_id[i] > max_value) {
88 max_slot = i;
89 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000090 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000091
92 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000093}
94
95namespace {
96class ArgsCrashTracerInfo {
97 llvm::SmallString<1024> CrashString;
98 llvm::SmallString<1024> AggregateString;
99 unsigned crashtracerSlot;
100public:
101 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
102 : crashtracerSlot(0)
103 {
104 {
105 llvm::raw_svector_ostream Out(CrashString);
106 Out << "ClangCIndex [createTranslationUnitFromSourceFile]: clang";
107 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
108 E=Args.end(); I!=E; ++I)
109 Out << ' ' << *I;
110 }
111 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
112 AggregateString);
113 }
114
115 ~ArgsCrashTracerInfo() {
116 ResetCrashTracerInfo(crashtracerSlot);
117 }
118};
119}
120#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121#endif
122
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000123/// \brief The result of comparing two source ranges.
124enum RangeComparisonResult {
125 /// \brief Either the ranges overlap or one of the ranges is invalid.
126 RangeOverlap,
127
128 /// \brief The first range ends before the second range starts.
129 RangeBefore,
130
131 /// \brief The first range starts after the second range ends.
132 RangeAfter
133};
134
135/// \brief Compare two source ranges to determine their relative position in
136/// the translation unit.
137static RangeComparisonResult RangeCompare(SourceManager &SM,
138 SourceRange R1,
139 SourceRange R2) {
140 assert(R1.isValid() && "First range is invalid?");
141 assert(R2.isValid() && "Second range is invalid?");
142 if (SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
143 return RangeBefore;
144 if (SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
145 return RangeAfter;
146 return RangeOverlap;
147}
148
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000149/// \brief Translate a Clang source range into a CIndex source range.
150///
151/// Clang internally represents ranges where the end location points to the
152/// start of the token at the end. However, for external clients it is more
153/// useful to have a CXSourceRange be a proper half-open interval. This routine
154/// does the appropriate translation.
155CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
156 const LangOptions &LangOpts,
157 SourceRange R) {
158 // FIXME: This is largely copy-paste from
159 // TextDiagnosticPrinter::HighlightRange. When it is clear that this is what
160 // we want the two routines should be refactored.
161
162 // We want the last character in this location, so we will adjust the
163 // instantiation location accordingly.
164
165 // If the location is from a macro instantiation, get the end of the
166 // instantiation range.
167 SourceLocation EndLoc = R.getEnd();
168 SourceLocation InstLoc = SM.getInstantiationLoc(EndLoc);
169 if (EndLoc.isMacroID())
170 InstLoc = SM.getInstantiationRange(EndLoc).second;
171
172 // Measure the length token we're pointing at, so we can adjust the physical
173 // location in the file to point at the last character.
174 //
175 // FIXME: This won't cope with trigraphs or escaped newlines well. For that,
176 // we actually need a preprocessor, which isn't currently available
177 // here. Eventually, we'll switch the pointer data of
178 // CXSourceLocation/CXSourceRange to a translation unit (CXXUnit), so that the
179 // preprocessor will be available here. At that point, we can use
180 // Preprocessor::getLocForEndOfToken().
181 if (InstLoc.isValid()) {
182 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM, LangOpts);
183 // FIXME: Temporarily represent as closed range to preserve API
184 // compatibility.
185 if (Length) --Length;
186 EndLoc = EndLoc.getFileLocWithOffset(Length);
187 }
188
189 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
190 R.getBegin().getRawEncoding(),
191 EndLoc.getRawEncoding() };
192 return Result;
193}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000194
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000195//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000196// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000197//===----------------------------------------------------------------------===//
198
Steve Naroff89922f82009-08-31 00:59:03 +0000199namespace {
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000200
Douglas Gregorb1373d02010-01-20 20:59:29 +0000201// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000202class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000203 public TypeLocVisitor<CursorVisitor, bool>,
204 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000205{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000206 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000207 ASTUnit *TU;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208
209 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000210 CXCursor Parent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000211
212 /// \brief The declaration that serves at the parent of any statement or
213 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000214 Decl *StmtParent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000215
216 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000217 CXCursorVisitor Visitor;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000218
219 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220 CXClientData ClientData;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000221
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000222 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
223 // to the visitor. Declarations with a PCH level greater than this value will
224 // be suppressed.
225 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000226
227 /// \brief When valid, a source range to which the cursor should restrict
228 /// its search.
229 SourceRange RegionOfInterest;
230
Douglas Gregorb1373d02010-01-20 20:59:29 +0000231 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000232 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000233 using StmtVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000234
235 /// \brief Determine whether this particular source range comes before, comes
236 /// after, or overlaps the region of interest.
237 ///
238 /// \param R a source range retrieved from the abstract syntax tree.
239 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
240
Steve Naroff89922f82009-08-31 00:59:03 +0000241public:
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000242 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000243 unsigned MaxPCHLevel,
244 SourceRange RegionOfInterest = SourceRange())
245 : TU(TU), Visitor(Visitor), ClientData(ClientData),
246 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000247 {
248 Parent.kind = CXCursor_NoDeclFound;
249 Parent.data[0] = 0;
250 Parent.data[1] = 0;
251 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000252 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000253 }
254
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000255 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000256 bool VisitChildren(CXCursor Parent);
257
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000258 // Declaration visitors
Douglas Gregorb1373d02010-01-20 20:59:29 +0000259 bool VisitDeclContext(DeclContext *DC);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000260 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000261 bool VisitTypedefDecl(TypedefDecl *D);
262 bool VisitTagDecl(TagDecl *D);
263 bool VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000264 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000265 bool VisitFunctionDecl(FunctionDecl *ND);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000266 bool VisitFieldDecl(FieldDecl *D);
267 bool VisitVarDecl(VarDecl *);
268 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
Douglas Gregora59e3902010-01-21 23:27:09 +0000269 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000270 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000271 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000272 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
273 bool VisitObjCImplDecl(ObjCImplDecl *D);
274 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
275 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
276 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
277 // etc.
278 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
279 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
280 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000281
282 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000283 // FIXME: QualifiedTypeLoc doesn't provide any location information
284 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000285 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000286 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
287 bool VisitTagTypeLoc(TagTypeLoc TL);
288 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
289 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
290 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
291 bool VisitPointerTypeLoc(PointerTypeLoc TL);
292 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
293 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
294 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
295 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
296 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
297 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000298 // FIXME: Implement for TemplateSpecializationTypeLoc
299 // FIXME: Implement visitors here when the unimplemented TypeLocs get
300 // implemented
301 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
302 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregora59e3902010-01-21 23:27:09 +0000303
304 // Statement visitors
305 bool VisitStmt(Stmt *S);
306 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000307 // FIXME: LabelStmt label?
308 bool VisitIfStmt(IfStmt *S);
309 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000310 bool VisitWhileStmt(WhileStmt *S);
311 bool VisitForStmt(ForStmt *S);
Douglas Gregor336fd812010-01-23 00:40:08 +0000312
313 // Expression visitors
314 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
315 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
316 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000317};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000318
Ted Kremenekab188932010-01-05 19:32:54 +0000319} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000320
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000321RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000322 // Move the end of the input range to the end of the last token in that
323 // range.
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000324 SourceLocation NewEnd
325 = TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1);
326 if (NewEnd.isValid())
327 R.setEnd(NewEnd);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000328 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
329}
330
Douglas Gregorb1373d02010-01-20 20:59:29 +0000331/// \brief Visit the given cursor and, if requested by the visitor,
332/// its children.
333///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000334/// \param Cursor the cursor to visit.
335///
336/// \param CheckRegionOfInterest if true, then the caller already checked that
337/// this cursor is within the region of interest.
338///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000339/// \returns true if the visitation should be aborted, false if it
340/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000341bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000342 if (clang_isInvalid(Cursor.kind))
343 return false;
344
345 if (clang_isDeclaration(Cursor.kind)) {
346 Decl *D = getCursorDecl(Cursor);
347 assert(D && "Invalid declaration cursor");
348 if (D->getPCHLevel() > MaxPCHLevel)
349 return false;
350
351 if (D->isImplicit())
352 return false;
353 }
354
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000355 // If we have a range of interest, and this cursor doesn't intersect with it,
356 // we're done.
357 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbarf408f322010-02-14 08:32:05 +0000358 SourceRange Range =
359 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
360 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000361 return false;
362 }
363
Douglas Gregorb1373d02010-01-20 20:59:29 +0000364 switch (Visitor(Cursor, Parent, ClientData)) {
365 case CXChildVisit_Break:
366 return true;
367
368 case CXChildVisit_Continue:
369 return false;
370
371 case CXChildVisit_Recurse:
372 return VisitChildren(Cursor);
373 }
374
Douglas Gregorfd643772010-01-25 16:45:46 +0000375 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376}
377
378/// \brief Visit the children of the given cursor.
379///
380/// \returns true if the visitation should be aborted, false if it
381/// should continue.
382bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000383 if (clang_isReference(Cursor.kind)) {
384 // By definition, references have no children.
385 return false;
386 }
387
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388 // Set the Parent field to Cursor, then back to its old value once we're
389 // done.
390 class SetParentRAII {
391 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000392 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000393 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000394
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000396 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
397 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000398 {
399 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000400 if (clang_isDeclaration(Parent.kind))
401 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000402 }
403
404 ~SetParentRAII() {
405 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000406 if (clang_isDeclaration(Parent.kind))
407 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000409 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000410
411 if (clang_isDeclaration(Cursor.kind)) {
412 Decl *D = getCursorDecl(Cursor);
413 assert(D && "Invalid declaration cursor");
414 return Visit(D);
415 }
416
Douglas Gregora59e3902010-01-21 23:27:09 +0000417 if (clang_isStatement(Cursor.kind))
418 return Visit(getCursorStmt(Cursor));
419 if (clang_isExpression(Cursor.kind))
420 return Visit(getCursorExpr(Cursor));
421
Douglas Gregorb1373d02010-01-20 20:59:29 +0000422 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000423 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000424 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
425 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000426 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
427 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
428 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000429 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000430 return true;
431 }
432 } else {
433 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000435 }
436
437 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000438 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000439
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000441 return false;
442}
443
Douglas Gregorb1373d02010-01-20 20:59:29 +0000444bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000445 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000446 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000447 if (RegionOfInterest.isValid()) {
448 SourceRange R = (*I)->getSourceRange();
449 if (R.isInvalid())
450 continue;
451
452 switch (CompareRegionOfInterest(R)) {
453 case RangeBefore:
454 // This declaration comes before the region of interest; skip it.
455 continue;
456
457 case RangeAfter:
458 // This declaration comes after the region of interest; we're done.
459 return false;
460
461 case RangeOverlap:
462 // This declaration overlaps the region of interest; visit it.
463 break;
464 }
465 }
466
467 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468 return true;
469 }
470
471 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000472}
473
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000474bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
475 llvm_unreachable("Translation units are visited directly by Visit()");
476 return false;
477}
478
479bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
480 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
481 return Visit(TSInfo->getTypeLoc());
482
483 return false;
484}
485
486bool CursorVisitor::VisitTagDecl(TagDecl *D) {
487 return VisitDeclContext(D);
488}
489
490bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
491 if (Expr *Init = D->getInitExpr())
492 return Visit(MakeCXCursor(Init, StmtParent, TU));
493 return false;
494}
495
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000496bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
497 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
498 if (Visit(TSInfo->getTypeLoc()))
499 return true;
500
501 return false;
502}
503
Douglas Gregorb1373d02010-01-20 20:59:29 +0000504bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000505 if (VisitDeclaratorDecl(ND))
506 return true;
507
Douglas Gregora59e3902010-01-21 23:27:09 +0000508 if (ND->isThisDeclarationADefinition() &&
509 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
510 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000511
512 return false;
513}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000514
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000515bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
516 if (VisitDeclaratorDecl(D))
517 return true;
518
519 if (Expr *BitWidth = D->getBitWidth())
520 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
521
522 return false;
523}
524
525bool CursorVisitor::VisitVarDecl(VarDecl *D) {
526 if (VisitDeclaratorDecl(D))
527 return true;
528
529 if (Expr *Init = D->getInit())
530 return Visit(MakeCXCursor(Init, StmtParent, TU));
531
532 return false;
533}
534
535bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
536 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
537 // At the moment, we don't have information about locations in the return
538 // type.
539 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
540 PEnd = ND->param_end();
541 P != PEnd; ++P) {
542 if (Visit(MakeCXCursor(*P, TU)))
543 return true;
544 }
545
546 if (ND->isThisDeclarationADefinition() &&
547 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
548 return true;
549
550 return false;
551}
552
Douglas Gregora59e3902010-01-21 23:27:09 +0000553bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
554 return VisitDeclContext(D);
555}
556
Douglas Gregorb1373d02010-01-20 20:59:29 +0000557bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000558 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
559 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000560 return true;
561
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000562 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
563 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
564 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000565 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000566 return true;
567
Douglas Gregora59e3902010-01-21 23:27:09 +0000568 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000569}
570
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000571bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
572 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
573 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
574 E = PID->protocol_end(); I != E; ++I, ++PL)
575 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
576 return true;
577
578 return VisitObjCContainerDecl(PID);
579}
580
Douglas Gregorb1373d02010-01-20 20:59:29 +0000581bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000582 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000583 if (D->getSuperClass() &&
584 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000585 D->getSuperClassLoc(),
586 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000587 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000588
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000589 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
590 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
591 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000592 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000593 return true;
594
Douglas Gregora59e3902010-01-21 23:27:09 +0000595 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000596}
597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
599 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000600}
601
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000602bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
603 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
604 D->getLocation(), TU)))
605 return true;
606
607 return VisitObjCImplDecl(D);
608}
609
610bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
611#if 0
612 // Issue callbacks for super class.
613 // FIXME: No source location information!
614 if (D->getSuperClass() &&
615 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
616 D->getSuperClassLoc(),
617 TU)))
618 return true;
619#endif
620
621 return VisitObjCImplDecl(D);
622}
623
624bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
625 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
626 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
627 E = D->protocol_end();
628 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000629 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000630 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000631
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000632 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000633}
634
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000635bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
636 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
637 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
638 return true;
639
640 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000641}
642
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000643bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
644 ASTContext &Context = TU->getASTContext();
645
646 // Some builtin types (such as Objective-C's "id", "sel", and
647 // "Class") have associated declarations. Create cursors for those.
648 QualType VisitType;
649 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
650 case BuiltinType::Void:
651 case BuiltinType::Bool:
652 case BuiltinType::Char_U:
653 case BuiltinType::UChar:
654 case BuiltinType::Char16:
655 case BuiltinType::Char32:
656 case BuiltinType::UShort:
657 case BuiltinType::UInt:
658 case BuiltinType::ULong:
659 case BuiltinType::ULongLong:
660 case BuiltinType::UInt128:
661 case BuiltinType::Char_S:
662 case BuiltinType::SChar:
663 case BuiltinType::WChar:
664 case BuiltinType::Short:
665 case BuiltinType::Int:
666 case BuiltinType::Long:
667 case BuiltinType::LongLong:
668 case BuiltinType::Int128:
669 case BuiltinType::Float:
670 case BuiltinType::Double:
671 case BuiltinType::LongDouble:
672 case BuiltinType::NullPtr:
673 case BuiltinType::Overload:
674 case BuiltinType::Dependent:
675 break;
676
677 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
678 break;
679
680 case BuiltinType::ObjCId:
681 VisitType = Context.getObjCIdType();
682 break;
683
684 case BuiltinType::ObjCClass:
685 VisitType = Context.getObjCClassType();
686 break;
687
688 case BuiltinType::ObjCSel:
689 VisitType = Context.getObjCSelType();
690 break;
691 }
692
693 if (!VisitType.isNull()) {
694 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
695 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
696 TU));
697 }
698
699 return false;
700}
701
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000702bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
703 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
704}
705
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000706bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
707 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
708}
709
710bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
711 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
712}
713
714bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
715 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
716 return true;
717
718 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
719 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
720 TU)))
721 return true;
722 }
723
724 return false;
725}
726
727bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
728 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
729 return true;
730
731 if (TL.hasProtocolsAsWritten()) {
732 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
733 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
734 TL.getProtocolLoc(I),
735 TU)))
736 return true;
737 }
738 }
739
740 return false;
741}
742
743bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
744 return Visit(TL.getPointeeLoc());
745}
746
747bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
748 return Visit(TL.getPointeeLoc());
749}
750
751bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
752 return Visit(TL.getPointeeLoc());
753}
754
755bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
756 return Visit(TL.getPointeeLoc());
757}
758
759bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
760 return Visit(TL.getPointeeLoc());
761}
762
763bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
764 if (Visit(TL.getResultLoc()))
765 return true;
766
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000767 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
768 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
769 return true;
770
771 return false;
772}
773
774bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
775 if (Visit(TL.getElementLoc()))
776 return true;
777
778 if (Expr *Size = TL.getSizeExpr())
779 return Visit(MakeCXCursor(Size, StmtParent, TU));
780
781 return false;
782}
783
Douglas Gregor2332c112010-01-21 20:48:56 +0000784bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
785 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
786}
787
788bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
789 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
790 return Visit(TSInfo->getTypeLoc());
791
792 return false;
793}
794
Douglas Gregora59e3902010-01-21 23:27:09 +0000795bool CursorVisitor::VisitStmt(Stmt *S) {
796 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
797 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000798 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000799 return true;
800 }
801
802 return false;
803}
804
805bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
806 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
807 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000808 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000809 return true;
810 }
811
812 return false;
813}
814
Douglas Gregorf5bab412010-01-22 01:00:11 +0000815bool CursorVisitor::VisitIfStmt(IfStmt *S) {
816 if (VarDecl *Var = S->getConditionVariable()) {
817 if (Visit(MakeCXCursor(Var, TU)))
818 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000819 }
Douglas Gregorf5bab412010-01-22 01:00:11 +0000820
Douglas Gregor263b47b2010-01-25 16:12:32 +0000821 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
822 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000823 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
824 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000825 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
826 return true;
827
828 return false;
829}
830
831bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
832 if (VarDecl *Var = S->getConditionVariable()) {
833 if (Visit(MakeCXCursor(Var, TU)))
834 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000835 }
836
837 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
838 return true;
839 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
840 return true;
841
842 return false;
843}
844
845bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
846 if (VarDecl *Var = S->getConditionVariable()) {
847 if (Visit(MakeCXCursor(Var, TU)))
848 return true;
849 }
850
851 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
852 return true;
853 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000854 return true;
855
Douglas Gregor263b47b2010-01-25 16:12:32 +0000856 return false;
857}
858
859bool CursorVisitor::VisitForStmt(ForStmt *S) {
860 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
861 return true;
862 if (VarDecl *Var = S->getConditionVariable()) {
863 if (Visit(MakeCXCursor(Var, TU)))
864 return true;
865 }
866
867 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
868 return true;
869 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
870 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000871 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
872 return true;
873
874 return false;
875}
876
Douglas Gregor336fd812010-01-23 00:40:08 +0000877bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
878 if (E->isArgumentType()) {
879 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
880 return Visit(TSInfo->getTypeLoc());
881
882 return false;
883 }
884
885 return VisitExpr(E);
886}
887
888bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
889 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
890 if (Visit(TSInfo->getTypeLoc()))
891 return true;
892
893 return VisitCastExpr(E);
894}
895
896bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
897 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
898 if (Visit(TSInfo->getTypeLoc()))
899 return true;
900
901 return VisitExpr(E);
902}
903
Daniel Dunbar140fce22010-01-12 02:34:07 +0000904CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000905 CXString Str;
906 if (DupString) {
907 Str.Spelling = strdup(String);
908 Str.MustFreeString = 1;
909 } else {
910 Str.Spelling = String;
911 Str.MustFreeString = 0;
912 }
913 return Str;
914}
915
Douglas Gregorfc8ea232010-01-26 17:06:03 +0000916CXString CIndexer::createCXString(llvm::StringRef String, bool DupString) {
917 CXString Result;
918 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
919 char *Spelling = (char *)malloc(String.size() + 1);
920 memmove(Spelling, String.data(), String.size());
921 Spelling[String.size()] = 0;
922 Result.Spelling = Spelling;
923 Result.MustFreeString = 1;
924 } else {
925 Result.Spelling = String.data();
926 Result.MustFreeString = 0;
927 }
928 return Result;
929}
930
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000931extern "C" {
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000932CXIndex clang_createIndex(int excludeDeclarationsFromPCH) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000933 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000934 if (excludeDeclarationsFromPCH)
935 CIdxr->setOnlyLocalDecls();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000936 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000937}
938
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000939void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000940 if (CIdx)
941 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000942}
943
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000944void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000945 if (CIdx) {
946 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
947 CXXIdx->setUseExternalASTGeneration(value);
948 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000949}
950
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000951CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000952 const char *ast_filename,
953 CXDiagnosticCallback diag_callback,
954 CXClientData diag_client_data) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000955 if (!CIdx)
956 return 0;
957
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000958 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000959
Douglas Gregor5352ac02010-01-28 00:27:43 +0000960 // Configure the diagnostics.
961 DiagnosticOptions DiagOpts;
962 llvm::OwningPtr<Diagnostic> Diags;
963 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
964 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
965 Diags->setClient(&DiagClient);
966
967 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000968 CXXIdx->getOnlyLocalDecls(),
969 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000970}
971
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000972CXTranslationUnit
973clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
974 const char *source_filename,
975 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000976 const char **command_line_args,
977 unsigned num_unsaved_files,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000978 struct CXUnsavedFile *unsaved_files,
979 CXDiagnosticCallback diag_callback,
980 CXClientData diag_client_data) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000981 if (!CIdx)
982 return 0;
983
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000984 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
985
Douglas Gregor5352ac02010-01-28 00:27:43 +0000986 // Configure the diagnostics.
987 DiagnosticOptions DiagOpts;
988 llvm::OwningPtr<Diagnostic> Diags;
989 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
990 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
991 Diags->setClient(&DiagClient);
992
Douglas Gregor4db64a42010-01-23 00:14:00 +0000993 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
994 for (unsigned I = 0; I != num_unsaved_files; ++I) {
995 const llvm::MemoryBuffer *Buffer
996 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
997 unsaved_files[I].Contents + unsaved_files[I].Length,
998 unsaved_files[I].Filename);
999 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1000 Buffer));
1001 }
1002
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001003 if (!CXXIdx->getUseExternalASTGeneration()) {
1004 llvm::SmallVector<const char *, 16> Args;
1005
1006 // The 'source_filename' argument is optional. If the caller does not
1007 // specify it then it is assumed that the source file is specified
1008 // in the actual argument list.
1009 if (source_filename)
1010 Args.push_back(source_filename);
1011 Args.insert(Args.end(), command_line_args,
1012 command_line_args + num_command_line_args);
1013
Douglas Gregor5352ac02010-01-28 00:27:43 +00001014 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001015
Ted Kremenek29b72842010-01-07 22:49:05 +00001016#ifdef USE_CRASHTRACER
1017 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +00001018#endif
1019
Daniel Dunbar94220972009-12-05 02:17:18 +00001020 llvm::OwningPtr<ASTUnit> Unit(
1021 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor5352ac02010-01-28 00:27:43 +00001022 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001023 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +00001024 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +00001025 /* UseBumpAllocator = */ true,
1026 RemappedFiles.data(),
1027 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +00001028
Daniel Dunbar94220972009-12-05 02:17:18 +00001029 // FIXME: Until we have broader testing, just drop the entire AST if we
1030 // encountered an error.
Douglas Gregor5352ac02010-01-28 00:27:43 +00001031 if (NumErrors != Diags->getNumErrors())
Daniel Dunbar94220972009-12-05 02:17:18 +00001032 return 0;
1033
1034 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001035 }
1036
Ted Kremenek139ba862009-10-22 00:03:57 +00001037 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001038 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001039
Ted Kremenek139ba862009-10-22 00:03:57 +00001040 // First add the complete path to the 'clang' executable.
1041 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001042 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001043
Ted Kremenek139ba862009-10-22 00:03:57 +00001044 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001045 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001046
Ted Kremenek139ba862009-10-22 00:03:57 +00001047 // The 'source_filename' argument is optional. If the caller does not
1048 // specify it then it is assumed that the source file is specified
1049 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001050 if (source_filename)
1051 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001052
Steve Naroff37b5ac22009-10-15 20:50:09 +00001053 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001054 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +00001055 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +00001056 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001057
Douglas Gregor4db64a42010-01-23 00:14:00 +00001058 // Remap any unsaved files to temporary files.
1059 std::vector<llvm::sys::Path> TemporaryFiles;
1060 std::vector<std::string> RemapArgs;
1061 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1062 return 0;
1063
1064 // The pointers into the elements of RemapArgs are stable because we
1065 // won't be adding anything to RemapArgs after this point.
1066 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1067 argv.push_back(RemapArgs[i].c_str());
1068
Ted Kremenek139ba862009-10-22 00:03:57 +00001069 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1070 for (int i = 0; i < num_command_line_args; ++i)
1071 if (const char *arg = command_line_args[i]) {
1072 if (strcmp(arg, "-o") == 0) {
1073 ++i; // Also skip the matching argument.
1074 continue;
1075 }
1076 if (strcmp(arg, "-emit-ast") == 0 ||
1077 strcmp(arg, "-c") == 0 ||
1078 strcmp(arg, "-fsyntax-only") == 0) {
1079 continue;
1080 }
1081
1082 // Keep the argument.
1083 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001084 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001085
Douglas Gregord93256e2010-01-28 06:00:51 +00001086 // Generate a temporary name for the diagnostics file.
1087 char tmpFileResults[L_tmpnam];
1088 char *tmpResultsFileName = tmpnam(tmpFileResults);
1089 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
1090 TemporaryFiles.push_back(DiagnosticsFile);
1091 argv.push_back("-fdiagnostics-binary");
1092
Ted Kremenek139ba862009-10-22 00:03:57 +00001093 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001094 argv.push_back(NULL);
1095
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001096 // Invoke 'clang'.
1097 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1098 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001099 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001100 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1101 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001102 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001103 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001104 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001105
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001106 if (!ErrMsg.empty()) {
1107 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001108 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001109 I != E; ++I) {
1110 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001111 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001112 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001113 }
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001114
1115 Diags->Report(diag::err_fe_clang) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001116 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001117
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001118 // FIXME: Parse the (redirected) standard error to emit diagnostics.
1119
Douglas Gregor5352ac02010-01-28 00:27:43 +00001120 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001121 CXXIdx->getOnlyLocalDecls(),
1122 /* UseBumpAllocator = */ true,
1123 RemappedFiles.data(),
1124 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001125 if (ATU)
1126 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001127
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001128 // FIXME: Currently we don't report diagnostics on invalid ASTs.
1129 if (ATU)
1130 ReportSerializedDiagnostics(DiagnosticsFile, *Diags,
1131 num_unsaved_files, unsaved_files,
1132 ATU->getASTContext().getLangOptions());
Douglas Gregord93256e2010-01-28 06:00:51 +00001133
Douglas Gregor4db64a42010-01-23 00:14:00 +00001134 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1135 TemporaryFiles[i].eraseFromDisk();
1136
Steve Naroffe19944c2009-10-15 22:23:48 +00001137 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001138}
1139
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001140void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001141 if (CTUnit)
1142 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001143}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001144
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001145CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001146 if (!CTUnit)
1147 return CIndexer::createCXString("");
1148
Steve Naroff77accc12009-09-03 18:19:54 +00001149 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001150 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1151 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001152}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001153
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001154CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001155 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001156 return Result;
1157}
1158
Ted Kremenekfb480492010-01-13 21:46:36 +00001159} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001160
Ted Kremenekfb480492010-01-13 21:46:36 +00001161//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001162// CXSourceLocation and CXSourceRange Operations.
1163//===----------------------------------------------------------------------===//
1164
Douglas Gregorb9790342010-01-22 21:44:22 +00001165extern "C" {
1166CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001167 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001168 return Result;
1169}
1170
1171unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001172 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1173 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1174 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001175}
1176
1177CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1178 CXFile file,
1179 unsigned line,
1180 unsigned column) {
1181 if (!tu)
1182 return clang_getNullLocation();
1183
1184 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1185 SourceLocation SLoc
1186 = CXXUnit->getSourceManager().getLocation(
1187 static_cast<const FileEntry *>(file),
1188 line, column);
1189
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001190 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00001191}
1192
Douglas Gregor5352ac02010-01-28 00:27:43 +00001193CXSourceRange clang_getNullRange() {
1194 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1195 return Result;
1196}
Douglas Gregorb9790342010-01-22 21:44:22 +00001197
Douglas Gregor5352ac02010-01-28 00:27:43 +00001198CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1199 if (begin.ptr_data[0] != end.ptr_data[0] ||
1200 begin.ptr_data[1] != end.ptr_data[1])
1201 return clang_getNullRange();
1202
1203 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1204 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001205 return Result;
1206}
1207
Douglas Gregor46766dc2010-01-26 19:19:08 +00001208void clang_getInstantiationLocation(CXSourceLocation location,
1209 CXFile *file,
1210 unsigned *line,
1211 unsigned *column,
1212 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001213 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1214
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001215 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00001216 if (file)
1217 *file = 0;
1218 if (line)
1219 *line = 0;
1220 if (column)
1221 *column = 0;
1222 if (offset)
1223 *offset = 0;
1224 return;
1225 }
1226
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001227 const SourceManager &SM =
1228 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001229 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001230
1231 if (file)
1232 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1233 if (line)
1234 *line = SM.getInstantiationLineNumber(InstLoc);
1235 if (column)
1236 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001237 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001238 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001239}
1240
Douglas Gregor1db19de2010-01-19 21:36:55 +00001241CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001242 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1243 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001244 return Result;
1245}
1246
1247CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00001248 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00001249 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001250 return Result;
1251}
1252
Douglas Gregorb9790342010-01-22 21:44:22 +00001253} // end: extern "C"
1254
Douglas Gregor1db19de2010-01-19 21:36:55 +00001255//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001256// CXFile Operations.
1257//===----------------------------------------------------------------------===//
1258
1259extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001260const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001261 if (!SFile)
1262 return 0;
1263
Steve Naroff88145032009-10-27 14:35:18 +00001264 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1265 return FEnt->getName();
1266}
1267
1268time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001269 if (!SFile)
1270 return 0;
1271
Steve Naroff88145032009-10-27 14:35:18 +00001272 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1273 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001274}
Douglas Gregorb9790342010-01-22 21:44:22 +00001275
1276CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1277 if (!tu)
1278 return 0;
1279
1280 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1281
1282 FileManager &FMgr = CXXUnit->getFileManager();
1283 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1284 return const_cast<FileEntry *>(File);
1285}
1286
Ted Kremenekfb480492010-01-13 21:46:36 +00001287} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001288
Ted Kremenekfb480492010-01-13 21:46:36 +00001289//===----------------------------------------------------------------------===//
1290// CXCursor Operations.
1291//===----------------------------------------------------------------------===//
1292
Ted Kremenekfb480492010-01-13 21:46:36 +00001293static Decl *getDeclFromExpr(Stmt *E) {
1294 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1295 return RefExpr->getDecl();
1296 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1297 return ME->getMemberDecl();
1298 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1299 return RE->getDecl();
1300
1301 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1302 return getDeclFromExpr(CE->getCallee());
1303 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1304 return getDeclFromExpr(CE->getSubExpr());
1305 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1306 return OME->getMethodDecl();
1307
1308 return 0;
1309}
1310
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001311static SourceLocation getLocationFromExpr(Expr *E) {
1312 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1313 return /*FIXME:*/Msg->getLeftLoc();
1314 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1315 return DRE->getLocation();
1316 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1317 return Member->getMemberLoc();
1318 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1319 return Ivar->getLocation();
1320 return E->getLocStart();
1321}
1322
Ted Kremenekfb480492010-01-13 21:46:36 +00001323extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001324
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001325unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001326 CXCursorVisitor visitor,
1327 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001328 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001329
1330 unsigned PCHLevel = Decl::MaxPCHLevel;
1331
1332 // Set the PCHLevel to filter out unwanted decls if requested.
1333 if (CXXUnit->getOnlyLocalDecls()) {
1334 PCHLevel = 0;
1335
1336 // If the main input was an AST, bump the level.
1337 if (CXXUnit->isMainFileAST())
1338 ++PCHLevel;
1339 }
1340
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001341 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001342 return CursorVis.VisitChildren(parent);
1343}
1344
Douglas Gregor78205d42010-01-20 21:45:58 +00001345static CXString getDeclSpelling(Decl *D) {
1346 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1347 if (!ND)
1348 return CIndexer::createCXString("");
1349
1350 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1351 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1352 true);
1353
1354 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1355 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1356 // and returns different names. NamedDecl returns the class name and
1357 // ObjCCategoryImplDecl returns the category name.
1358 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1359
1360 if (ND->getIdentifier())
1361 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1362
1363 return CIndexer::createCXString("");
1364}
1365
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001366CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001367 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001368 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001369
Steve Narofff334b4e2009-09-02 18:26:48 +00001370 if (clang_isReference(C.kind)) {
1371 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001372 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001373 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1374 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001375 }
1376 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001377 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1378 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001379 }
1380 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001381 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001382 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001383 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001384 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001385 case CXCursor_TypeRef: {
1386 TypeDecl *Type = getCursorTypeRef(C).first;
1387 assert(Type && "Missing type decl");
1388
1389 return CIndexer::createCXString(
1390 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1391 true);
1392 }
1393
Daniel Dunbaracca7252009-11-30 20:42:49 +00001394 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001395 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001396 }
1397 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001398
1399 if (clang_isExpression(C.kind)) {
1400 Decl *D = getDeclFromExpr(getCursorExpr(C));
1401 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001402 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001403 return CIndexer::createCXString("");
1404 }
1405
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001406 if (clang_isDeclaration(C.kind))
1407 return getDeclSpelling(getCursorDecl(C));
1408
1409 return CIndexer::createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001410}
1411
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001412const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001413 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001414 case CXCursor_FunctionDecl: return "FunctionDecl";
1415 case CXCursor_TypedefDecl: return "TypedefDecl";
1416 case CXCursor_EnumDecl: return "EnumDecl";
1417 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1418 case CXCursor_StructDecl: return "StructDecl";
1419 case CXCursor_UnionDecl: return "UnionDecl";
1420 case CXCursor_ClassDecl: return "ClassDecl";
1421 case CXCursor_FieldDecl: return "FieldDecl";
1422 case CXCursor_VarDecl: return "VarDecl";
1423 case CXCursor_ParmDecl: return "ParmDecl";
1424 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1425 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1426 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1427 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1428 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1429 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1430 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001431 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1432 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001433 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001434 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1435 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1436 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001437 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001438 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1439 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1440 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1441 case CXCursor_CallExpr: return "CallExpr";
1442 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1443 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001444 case CXCursor_InvalidFile: return "InvalidFile";
1445 case CXCursor_NoDeclFound: return "NoDeclFound";
1446 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001447 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001448 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001449
1450 llvm_unreachable("Unhandled CXCursorKind");
1451 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001452}
Steve Naroff89922f82009-08-31 00:59:03 +00001453
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001454enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1455 CXCursor parent,
1456 CXClientData client_data) {
1457 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1458 *BestCursor = cursor;
1459 return CXChildVisit_Recurse;
1460}
1461
Douglas Gregorb9790342010-01-22 21:44:22 +00001462CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1463 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001464 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001465
Douglas Gregorb9790342010-01-22 21:44:22 +00001466 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1467
Ted Kremeneka297de22010-01-25 22:34:44 +00001468 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001469 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1470 if (SLoc.isValid()) {
Daniel Dunbar19e4a072010-02-14 10:02:42 +00001471 SourceRange RegionOfInterest(SLoc, SLoc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001472
1473 // FIXME: Would be great to have a "hint" cursor, then walk from that
1474 // hint cursor upward until we find a cursor whose source range encloses
1475 // the region of interest, rather than starting from the translation unit.
1476 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1477 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1478 Decl::MaxPCHLevel, RegionOfInterest);
1479 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001480 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001481 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001482}
1483
Ted Kremenek73885552009-11-17 19:28:59 +00001484CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001485 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001486}
1487
1488unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001489 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001490}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001491
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001492unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001493 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1494}
1495
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001496unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001497 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1498}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001499
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001500unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001501 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1502}
1503
Douglas Gregor97b98722010-01-19 23:20:36 +00001504unsigned clang_isExpression(enum CXCursorKind K) {
1505 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1506}
1507
1508unsigned clang_isStatement(enum CXCursorKind K) {
1509 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1510}
1511
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001512unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1513 return K == CXCursor_TranslationUnit;
1514}
1515
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001516CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001517 return C.kind;
1518}
1519
Douglas Gregor98258af2010-01-18 22:46:11 +00001520CXSourceLocation clang_getCursorLocation(CXCursor C) {
1521 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001522 switch (C.kind) {
1523 case CXCursor_ObjCSuperClassRef: {
1524 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1525 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001526 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001527 }
1528
1529 case CXCursor_ObjCProtocolRef: {
1530 std::pair<ObjCProtocolDecl *, SourceLocation> P
1531 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001532 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001533 }
1534
1535 case CXCursor_ObjCClassRef: {
1536 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1537 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001538 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001539 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001540
1541 case CXCursor_TypeRef: {
1542 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001543 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001544 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001545
Douglas Gregorf46034a2010-01-18 23:41:10 +00001546 default:
1547 // FIXME: Need a way to enumerate all non-reference cases.
1548 llvm_unreachable("Missed a reference kind");
1549 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001550 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001551
1552 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001553 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001554 getLocationFromExpr(getCursorExpr(C)));
1555
Douglas Gregor5352ac02010-01-28 00:27:43 +00001556 if (!getCursorDecl(C))
1557 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001558
Douglas Gregorf46034a2010-01-18 23:41:10 +00001559 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001560 SourceLocation Loc = D->getLocation();
1561 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1562 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001563 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001564}
Douglas Gregora7bde202010-01-19 00:34:46 +00001565
1566CXSourceRange clang_getCursorExtent(CXCursor C) {
1567 if (clang_isReference(C.kind)) {
1568 switch (C.kind) {
1569 case CXCursor_ObjCSuperClassRef: {
1570 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1571 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001572 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001573 }
1574
1575 case CXCursor_ObjCProtocolRef: {
1576 std::pair<ObjCProtocolDecl *, SourceLocation> P
1577 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001578 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001579 }
1580
1581 case CXCursor_ObjCClassRef: {
1582 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1583 = getCursorObjCClassRef(C);
1584
Ted Kremeneka297de22010-01-25 22:34:44 +00001585 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001586 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001587
1588 case CXCursor_TypeRef: {
1589 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001590 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001591 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001592
Douglas Gregora7bde202010-01-19 00:34:46 +00001593 default:
1594 // FIXME: Need a way to enumerate all non-reference cases.
1595 llvm_unreachable("Missed a reference kind");
1596 }
1597 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001598
1599 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001600 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001601 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001602
1603 if (clang_isStatement(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001604 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001605 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001606
Douglas Gregor5352ac02010-01-28 00:27:43 +00001607 if (!getCursorDecl(C))
1608 return clang_getNullRange();
Douglas Gregora7bde202010-01-19 00:34:46 +00001609
1610 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001611 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001612}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001613
1614CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001615 if (clang_isInvalid(C.kind))
1616 return clang_getNullCursor();
1617
1618 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001619 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001620 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001621
Douglas Gregor97b98722010-01-19 23:20:36 +00001622 if (clang_isExpression(C.kind)) {
1623 Decl *D = getDeclFromExpr(getCursorExpr(C));
1624 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001625 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001626 return clang_getNullCursor();
1627 }
1628
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001629 if (!clang_isReference(C.kind))
1630 return clang_getNullCursor();
1631
1632 switch (C.kind) {
1633 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001634 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001635
1636 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001637 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001638
1639 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001640 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001641
1642 case CXCursor_TypeRef:
1643 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001644
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001645 default:
1646 // We would prefer to enumerate all non-reference cursor kinds here.
1647 llvm_unreachable("Unhandled reference cursor kind");
1648 break;
1649 }
1650 }
1651
1652 return clang_getNullCursor();
1653}
1654
Douglas Gregorb6998662010-01-19 19:34:47 +00001655CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001656 if (clang_isInvalid(C.kind))
1657 return clang_getNullCursor();
1658
1659 ASTUnit *CXXUnit = getCursorASTUnit(C);
1660
Douglas Gregorb6998662010-01-19 19:34:47 +00001661 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001662 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001663 C = clang_getCursorReferenced(C);
1664 WasReference = true;
1665 }
1666
1667 if (!clang_isDeclaration(C.kind))
1668 return clang_getNullCursor();
1669
1670 Decl *D = getCursorDecl(C);
1671 if (!D)
1672 return clang_getNullCursor();
1673
1674 switch (D->getKind()) {
1675 // Declaration kinds that don't really separate the notions of
1676 // declaration and definition.
1677 case Decl::Namespace:
1678 case Decl::Typedef:
1679 case Decl::TemplateTypeParm:
1680 case Decl::EnumConstant:
1681 case Decl::Field:
1682 case Decl::ObjCIvar:
1683 case Decl::ObjCAtDefsField:
1684 case Decl::ImplicitParam:
1685 case Decl::ParmVar:
1686 case Decl::NonTypeTemplateParm:
1687 case Decl::TemplateTemplateParm:
1688 case Decl::ObjCCategoryImpl:
1689 case Decl::ObjCImplementation:
1690 case Decl::LinkageSpec:
1691 case Decl::ObjCPropertyImpl:
1692 case Decl::FileScopeAsm:
1693 case Decl::StaticAssert:
1694 case Decl::Block:
1695 return C;
1696
1697 // Declaration kinds that don't make any sense here, but are
1698 // nonetheless harmless.
1699 case Decl::TranslationUnit:
1700 case Decl::Template:
1701 case Decl::ObjCContainer:
1702 break;
1703
1704 // Declaration kinds for which the definition is not resolvable.
1705 case Decl::UnresolvedUsingTypename:
1706 case Decl::UnresolvedUsingValue:
1707 break;
1708
1709 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001710 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1711 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001712
1713 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001714 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001715
1716 case Decl::Enum:
1717 case Decl::Record:
1718 case Decl::CXXRecord:
1719 case Decl::ClassTemplateSpecialization:
1720 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001721 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001722 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001723 return clang_getNullCursor();
1724
1725 case Decl::Function:
1726 case Decl::CXXMethod:
1727 case Decl::CXXConstructor:
1728 case Decl::CXXDestructor:
1729 case Decl::CXXConversion: {
1730 const FunctionDecl *Def = 0;
1731 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001732 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001733 return clang_getNullCursor();
1734 }
1735
1736 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001737 // Ask the variable if it has a definition.
1738 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1739 return MakeCXCursor(Def, CXXUnit);
1740 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001741 }
1742
1743 case Decl::FunctionTemplate: {
1744 const FunctionDecl *Def = 0;
1745 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001746 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001747 return clang_getNullCursor();
1748 }
1749
1750 case Decl::ClassTemplate: {
1751 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001752 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001753 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001754 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1755 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001756 return clang_getNullCursor();
1757 }
1758
1759 case Decl::Using: {
1760 UsingDecl *Using = cast<UsingDecl>(D);
1761 CXCursor Def = clang_getNullCursor();
1762 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1763 SEnd = Using->shadow_end();
1764 S != SEnd; ++S) {
1765 if (Def != clang_getNullCursor()) {
1766 // FIXME: We have no way to return multiple results.
1767 return clang_getNullCursor();
1768 }
1769
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001770 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1771 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001772 }
1773
1774 return Def;
1775 }
1776
1777 case Decl::UsingShadow:
1778 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001779 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1780 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001781
1782 case Decl::ObjCMethod: {
1783 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1784 if (Method->isThisDeclarationADefinition())
1785 return C;
1786
1787 // Dig out the method definition in the associated
1788 // @implementation, if we have it.
1789 // FIXME: The ASTs should make finding the definition easier.
1790 if (ObjCInterfaceDecl *Class
1791 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1792 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1793 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1794 Method->isInstanceMethod()))
1795 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001796 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001797
1798 return clang_getNullCursor();
1799 }
1800
1801 case Decl::ObjCCategory:
1802 if (ObjCCategoryImplDecl *Impl
1803 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001804 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001805 return clang_getNullCursor();
1806
1807 case Decl::ObjCProtocol:
1808 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1809 return C;
1810 return clang_getNullCursor();
1811
1812 case Decl::ObjCInterface:
1813 // There are two notions of a "definition" for an Objective-C
1814 // class: the interface and its implementation. When we resolved a
1815 // reference to an Objective-C class, produce the @interface as
1816 // the definition; when we were provided with the interface,
1817 // produce the @implementation as the definition.
1818 if (WasReference) {
1819 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1820 return C;
1821 } else if (ObjCImplementationDecl *Impl
1822 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001823 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001824 return clang_getNullCursor();
1825
1826 case Decl::ObjCProperty:
1827 // FIXME: We don't really know where to find the
1828 // ObjCPropertyImplDecls that implement this property.
1829 return clang_getNullCursor();
1830
1831 case Decl::ObjCCompatibleAlias:
1832 if (ObjCInterfaceDecl *Class
1833 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1834 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001835 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001836
1837 return clang_getNullCursor();
1838
1839 case Decl::ObjCForwardProtocol: {
1840 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1841 if (Forward->protocol_size() == 1)
1842 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001843 MakeCXCursor(*Forward->protocol_begin(),
1844 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001845
1846 // FIXME: Cannot return multiple definitions.
1847 return clang_getNullCursor();
1848 }
1849
1850 case Decl::ObjCClass: {
1851 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1852 if (Class->size() == 1) {
1853 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1854 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001855 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001856 return clang_getNullCursor();
1857 }
1858
1859 // FIXME: Cannot return multiple definitions.
1860 return clang_getNullCursor();
1861 }
1862
1863 case Decl::Friend:
1864 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001865 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001866 return clang_getNullCursor();
1867
1868 case Decl::FriendTemplate:
1869 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001870 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001871 return clang_getNullCursor();
1872 }
1873
1874 return clang_getNullCursor();
1875}
1876
1877unsigned clang_isCursorDefinition(CXCursor C) {
1878 if (!clang_isDeclaration(C.kind))
1879 return 0;
1880
1881 return clang_getCursorDefinition(C) == C;
1882}
1883
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001884void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001885 const char **startBuf,
1886 const char **endBuf,
1887 unsigned *startLine,
1888 unsigned *startColumn,
1889 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001890 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001891 assert(getCursorDecl(C) && "CXCursor has null decl");
1892 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001893 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1894 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001895
Steve Naroff4ade6d62009-09-23 17:52:52 +00001896 SourceManager &SM = FD->getASTContext().getSourceManager();
1897 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1898 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1899 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1900 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1901 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1902 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1903}
Ted Kremenekfb480492010-01-13 21:46:36 +00001904
1905} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001906
Ted Kremenekfb480492010-01-13 21:46:36 +00001907//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001908// Token-based Operations.
1909//===----------------------------------------------------------------------===//
1910
1911/* CXToken layout:
1912 * int_data[0]: a CXTokenKind
1913 * int_data[1]: starting token location
1914 * int_data[2]: token length
1915 * int_data[3]: reserved
1916 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
1917 * otherwise unused.
1918 */
1919extern "C" {
1920
1921CXTokenKind clang_getTokenKind(CXToken CXTok) {
1922 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1923}
1924
1925CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1926 switch (clang_getTokenKind(CXTok)) {
1927 case CXToken_Identifier:
1928 case CXToken_Keyword:
1929 // We know we have an IdentifierInfo*, so use that.
1930 return CIndexer::createCXString(
1931 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
1932
1933 case CXToken_Literal: {
1934 // We have stashed the starting pointer in the ptr_data field. Use it.
1935 const char *Text = static_cast<const char *>(CXTok.ptr_data);
1936 return CIndexer::createCXString(llvm::StringRef(Text, CXTok.int_data[2]),
1937 true);
1938 }
1939
1940 case CXToken_Punctuation:
1941 case CXToken_Comment:
1942 break;
1943 }
1944
1945 // We have to find the starting buffer pointer the hard way, by
1946 // deconstructing the source location.
1947 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1948 if (!CXXUnit)
1949 return CIndexer::createCXString("");
1950
1951 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1952 std::pair<FileID, unsigned> LocInfo
1953 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1954 std::pair<const char *,const char *> Buffer
1955 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1956
1957 return CIndexer::createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1958 CXTok.int_data[2]),
1959 true);
1960}
1961
1962CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1963 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1964 if (!CXXUnit)
1965 return clang_getNullLocation();
1966
1967 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1968 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1969}
1970
1971CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1972 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001973 if (!CXXUnit)
1974 return clang_getNullRange();
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001975
1976 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
1977 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1978}
1979
1980void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1981 CXToken **Tokens, unsigned *NumTokens) {
1982 if (Tokens)
1983 *Tokens = 0;
1984 if (NumTokens)
1985 *NumTokens = 0;
1986
1987 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1988 if (!CXXUnit || !Tokens || !NumTokens)
1989 return;
1990
Daniel Dunbar85b988f2010-02-14 08:31:57 +00001991 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001992 if (R.isInvalid())
1993 return;
1994
1995 SourceManager &SourceMgr = CXXUnit->getSourceManager();
1996 std::pair<FileID, unsigned> BeginLocInfo
1997 = SourceMgr.getDecomposedLoc(R.getBegin());
1998 std::pair<FileID, unsigned> EndLocInfo
1999 = SourceMgr.getDecomposedLoc(R.getEnd());
2000
2001 // Cannot tokenize across files.
2002 if (BeginLocInfo.first != EndLocInfo.first)
2003 return;
2004
2005 // Create a lexer
2006 std::pair<const char *,const char *> Buffer
2007 = SourceMgr.getBufferData(BeginLocInfo.first);
2008 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2009 CXXUnit->getASTContext().getLangOptions(),
2010 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
2011 Lex.SetCommentRetentionState(true);
2012
2013 // Lex tokens until we hit the end of the range.
2014 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
2015 llvm::SmallVector<CXToken, 32> CXTokens;
2016 Token Tok;
2017 do {
2018 // Lex the next token
2019 Lex.LexFromRawLexer(Tok);
2020 if (Tok.is(tok::eof))
2021 break;
2022
2023 // Initialize the CXToken.
2024 CXToken CXTok;
2025
2026 // - Common fields
2027 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2028 CXTok.int_data[2] = Tok.getLength();
2029 CXTok.int_data[3] = 0;
2030
2031 // - Kind-specific fields
2032 if (Tok.isLiteral()) {
2033 CXTok.int_data[0] = CXToken_Literal;
2034 CXTok.ptr_data = (void *)Tok.getLiteralData();
2035 } else if (Tok.is(tok::identifier)) {
2036 // Lookup the identifier to determine whether we have a
2037 std::pair<FileID, unsigned> LocInfo
2038 = SourceMgr.getDecomposedLoc(Tok.getLocation());
2039 const char *StartPos
2040 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
2041 LocInfo.second;
2042 IdentifierInfo *II
2043 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2044 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2045 CXToken_Identifier
2046 : CXToken_Keyword;
2047 CXTok.ptr_data = II;
2048 } else if (Tok.is(tok::comment)) {
2049 CXTok.int_data[0] = CXToken_Comment;
2050 CXTok.ptr_data = 0;
2051 } else {
2052 CXTok.int_data[0] = CXToken_Punctuation;
2053 CXTok.ptr_data = 0;
2054 }
2055 CXTokens.push_back(CXTok);
2056 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2057
2058 if (CXTokens.empty())
2059 return;
2060
2061 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2062 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2063 *NumTokens = CXTokens.size();
2064}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002065
2066typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2067
2068enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2069 CXCursor parent,
2070 CXClientData client_data) {
2071 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2072
2073 // We only annotate the locations of declarations, simple
2074 // references, and expressions which directly reference something.
2075 CXCursorKind Kind = clang_getCursorKind(cursor);
2076 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2077 // Okay: We can annotate the location of this declaration with the
2078 // declaration or reference
2079 } else if (clang_isExpression(cursor.kind)) {
2080 if (Kind != CXCursor_DeclRefExpr &&
2081 Kind != CXCursor_MemberRefExpr &&
2082 Kind != CXCursor_ObjCMessageExpr)
2083 return CXChildVisit_Recurse;
2084
2085 CXCursor Referenced = clang_getCursorReferenced(cursor);
2086 if (Referenced == cursor || Referenced == clang_getNullCursor())
2087 return CXChildVisit_Recurse;
2088
2089 // Okay: we can annotate the location of this expression
2090 } else {
2091 // Nothing to annotate
2092 return CXChildVisit_Recurse;
2093 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002094
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002095 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2096 (*Data)[Loc.int_data] = cursor;
2097 return CXChildVisit_Recurse;
2098}
2099
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002100void clang_annotateTokens(CXTranslationUnit TU,
2101 CXToken *Tokens, unsigned NumTokens,
2102 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002103 if (NumTokens == 0)
2104 return;
2105
2106 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002107 for (unsigned I = 0; I != NumTokens; ++I)
2108 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002109
2110 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2111 if (!CXXUnit || !Tokens)
2112 return;
2113
2114 // Annotate all of the source locations in the region of interest that map
2115 SourceRange RegionOfInterest;
2116 RegionOfInterest.setBegin(
2117 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2118 SourceLocation End
2119 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2120 Tokens[NumTokens - 1]));
2121 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End,
2122 1));
2123 // FIXME: Would be great to have a "hint" cursor, then walk from that
2124 // hint cursor upward until we find a cursor whose source range encloses
2125 // the region of interest, rather than starting from the translation unit.
2126 AnnotateTokensData Annotated;
2127 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2128 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2129 Decl::MaxPCHLevel, RegionOfInterest);
2130 AnnotateVis.VisitChildren(Parent);
2131
2132 for (unsigned I = 0; I != NumTokens; ++I) {
2133 // Determine whether we saw a cursor at this token's location.
2134 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2135 if (Pos == Annotated.end())
2136 continue;
2137
2138 Cursors[I] = Pos->second;
2139 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002140}
2141
2142void clang_disposeTokens(CXTranslationUnit TU,
2143 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002144 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002145}
2146
2147} // end: extern "C"
2148
2149//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002150// CXString Operations.
2151//===----------------------------------------------------------------------===//
2152
2153extern "C" {
2154const char *clang_getCString(CXString string) {
2155 return string.Spelling;
2156}
2157
2158void clang_disposeString(CXString string) {
2159 if (string.MustFreeString && string.Spelling)
2160 free((void*)string.Spelling);
2161}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002162
Ted Kremenekfb480492010-01-13 21:46:36 +00002163} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002164
2165//===----------------------------------------------------------------------===//
2166// Misc. utility functions.
2167//===----------------------------------------------------------------------===//
2168
2169extern "C" {
2170
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00002171CXString clang_getClangVersion() {
2172 return CIndexer::createCXString(getClangFullVersion(), true);
Ted Kremenek04bb7162010-01-22 22:44:15 +00002173}
2174
2175} // end: extern "C"
2176