blob: dc1608bbc8bee3cdf820a971c55ab8d3fc9546e3 [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
Douglas Gregor1db19de2010-01-19 21:36:55 +0000149
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000150//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000152//===----------------------------------------------------------------------===//
153
Steve Naroff89922f82009-08-31 00:59:03 +0000154namespace {
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000155
Douglas Gregorb1373d02010-01-20 20:59:29 +0000156// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000157class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000158 public TypeLocVisitor<CursorVisitor, bool>,
159 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000160{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000161 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000162 ASTUnit *TU;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000163
164 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165 CXCursor Parent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000166
167 /// \brief The declaration that serves at the parent of any statement or
168 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000169 Decl *StmtParent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170
171 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000172 CXCursorVisitor Visitor;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173
174 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000175 CXClientData ClientData;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000176
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000177 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
178 // to the visitor. Declarations with a PCH level greater than this value will
179 // be suppressed.
180 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181
182 /// \brief When valid, a source range to which the cursor should restrict
183 /// its search.
184 SourceRange RegionOfInterest;
185
Douglas Gregorb1373d02010-01-20 20:59:29 +0000186 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000187 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000188 using StmtVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000189
190 /// \brief Determine whether this particular source range comes before, comes
191 /// after, or overlaps the region of interest.
192 ///
193 /// \param R a source range retrieved from the abstract syntax tree.
194 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
195
196 /// \brief Determine whether this particular source range comes before, comes
197 /// after, or overlaps the region of interest.
198 ///
199 /// \param CXR a source range retrieved from a cursor.
200 RangeComparisonResult CompareRegionOfInterest(CXSourceRange CXR);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000201
Steve Naroff89922f82009-08-31 00:59:03 +0000202public:
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000203 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000204 unsigned MaxPCHLevel,
205 SourceRange RegionOfInterest = SourceRange())
206 : TU(TU), Visitor(Visitor), ClientData(ClientData),
207 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000208 {
209 Parent.kind = CXCursor_NoDeclFound;
210 Parent.data[0] = 0;
211 Parent.data[1] = 0;
212 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000213 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000214 }
215
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000216 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000217 bool VisitChildren(CXCursor Parent);
218
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000219 // Declaration visitors
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220 bool VisitDeclContext(DeclContext *DC);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000221 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000222 bool VisitTypedefDecl(TypedefDecl *D);
223 bool VisitTagDecl(TagDecl *D);
224 bool VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000225 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000226 bool VisitFunctionDecl(FunctionDecl *ND);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000227 bool VisitFieldDecl(FieldDecl *D);
228 bool VisitVarDecl(VarDecl *);
229 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
Douglas Gregora59e3902010-01-21 23:27:09 +0000230 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000231 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000232 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000233 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
234 bool VisitObjCImplDecl(ObjCImplDecl *D);
235 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
236 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
237 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
238 // etc.
239 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
240 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
241 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000242
243 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000244 // FIXME: QualifiedTypeLoc doesn't provide any location information
245 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000246 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000247 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
248 bool VisitTagTypeLoc(TagTypeLoc TL);
249 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
250 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
251 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
252 bool VisitPointerTypeLoc(PointerTypeLoc TL);
253 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
254 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
255 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
256 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
257 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
258 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000259 // FIXME: Implement for TemplateSpecializationTypeLoc
260 // FIXME: Implement visitors here when the unimplemented TypeLocs get
261 // implemented
262 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
263 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregora59e3902010-01-21 23:27:09 +0000264
265 // Statement visitors
266 bool VisitStmt(Stmt *S);
267 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000268 // FIXME: LabelStmt label?
269 bool VisitIfStmt(IfStmt *S);
270 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000271 bool VisitWhileStmt(WhileStmt *S);
272 bool VisitForStmt(ForStmt *S);
Douglas Gregor336fd812010-01-23 00:40:08 +0000273
274 // Expression visitors
275 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
276 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
277 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000278};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000279
Ted Kremenekab188932010-01-05 19:32:54 +0000280} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000281
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000282RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
283 assert(RegionOfInterest.isValid() && "RangeCompare called with invalid range");
284 if (R.isInvalid())
285 return RangeOverlap;
286
287 // Move the end of the input range to the end of the last token in that
288 // range.
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000289 SourceLocation NewEnd
290 = TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1);
291 if (NewEnd.isValid())
292 R.setEnd(NewEnd);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000293 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
294}
295
296RangeComparisonResult CursorVisitor::CompareRegionOfInterest(CXSourceRange CXR) {
Ted Kremeneka297de22010-01-25 22:34:44 +0000297 return CompareRegionOfInterest(cxloc::translateSourceRange(CXR));
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000298}
299
Douglas Gregorb1373d02010-01-20 20:59:29 +0000300/// \brief Visit the given cursor and, if requested by the visitor,
301/// its children.
302///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000303/// \param Cursor the cursor to visit.
304///
305/// \param CheckRegionOfInterest if true, then the caller already checked that
306/// this cursor is within the region of interest.
307///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000308/// \returns true if the visitation should be aborted, false if it
309/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000310bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000311 if (clang_isInvalid(Cursor.kind))
312 return false;
313
314 if (clang_isDeclaration(Cursor.kind)) {
315 Decl *D = getCursorDecl(Cursor);
316 assert(D && "Invalid declaration cursor");
317 if (D->getPCHLevel() > MaxPCHLevel)
318 return false;
319
320 if (D->isImplicit())
321 return false;
322 }
323
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000324 // If we have a range of interest, and this cursor doesn't intersect with it,
325 // we're done.
326 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
327 CXSourceRange Range = clang_getCursorExtent(Cursor);
Ted Kremeneka297de22010-01-25 22:34:44 +0000328 if (cxloc::translateSourceRange(Range).isInvalid() ||
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000329 CompareRegionOfInterest(Range))
330 return false;
331 }
332
Douglas Gregorb1373d02010-01-20 20:59:29 +0000333 switch (Visitor(Cursor, Parent, ClientData)) {
334 case CXChildVisit_Break:
335 return true;
336
337 case CXChildVisit_Continue:
338 return false;
339
340 case CXChildVisit_Recurse:
341 return VisitChildren(Cursor);
342 }
343
Douglas Gregorfd643772010-01-25 16:45:46 +0000344 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000345}
346
347/// \brief Visit the children of the given cursor.
348///
349/// \returns true if the visitation should be aborted, false if it
350/// should continue.
351bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000352 if (clang_isReference(Cursor.kind)) {
353 // By definition, references have no children.
354 return false;
355 }
356
Douglas Gregorb1373d02010-01-20 20:59:29 +0000357 // Set the Parent field to Cursor, then back to its old value once we're
358 // done.
359 class SetParentRAII {
360 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000361 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000362 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000363
Douglas Gregorb1373d02010-01-20 20:59:29 +0000364 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000365 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
366 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000367 {
368 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000369 if (clang_isDeclaration(Parent.kind))
370 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371 }
372
373 ~SetParentRAII() {
374 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000375 if (clang_isDeclaration(Parent.kind))
376 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000378 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000379
380 if (clang_isDeclaration(Cursor.kind)) {
381 Decl *D = getCursorDecl(Cursor);
382 assert(D && "Invalid declaration cursor");
383 return Visit(D);
384 }
385
Douglas Gregora59e3902010-01-21 23:27:09 +0000386 if (clang_isStatement(Cursor.kind))
387 return Visit(getCursorStmt(Cursor));
388 if (clang_isExpression(Cursor.kind))
389 return Visit(getCursorExpr(Cursor));
390
Douglas Gregorb1373d02010-01-20 20:59:29 +0000391 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000392 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000393 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
394 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000395 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
396 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
397 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000398 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000399 return true;
400 }
401 } else {
402 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000403 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000404 }
405
406 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000408
Douglas Gregorb1373d02010-01-20 20:59:29 +0000409 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000410 return false;
411}
412
Douglas Gregorb1373d02010-01-20 20:59:29 +0000413bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000414 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000415 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000416 if (RegionOfInterest.isValid()) {
417 SourceRange R = (*I)->getSourceRange();
418 if (R.isInvalid())
419 continue;
420
421 switch (CompareRegionOfInterest(R)) {
422 case RangeBefore:
423 // This declaration comes before the region of interest; skip it.
424 continue;
425
426 case RangeAfter:
427 // This declaration comes after the region of interest; we're done.
428 return false;
429
430 case RangeOverlap:
431 // This declaration overlaps the region of interest; visit it.
432 break;
433 }
434 }
435
436 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000437 return true;
438 }
439
440 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000441}
442
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000443bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
444 llvm_unreachable("Translation units are visited directly by Visit()");
445 return false;
446}
447
448bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
449 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
450 return Visit(TSInfo->getTypeLoc());
451
452 return false;
453}
454
455bool CursorVisitor::VisitTagDecl(TagDecl *D) {
456 return VisitDeclContext(D);
457}
458
459bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
460 if (Expr *Init = D->getInitExpr())
461 return Visit(MakeCXCursor(Init, StmtParent, TU));
462 return false;
463}
464
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000465bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
466 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
467 if (Visit(TSInfo->getTypeLoc()))
468 return true;
469
470 return false;
471}
472
Douglas Gregorb1373d02010-01-20 20:59:29 +0000473bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000474 if (VisitDeclaratorDecl(ND))
475 return true;
476
Douglas Gregora59e3902010-01-21 23:27:09 +0000477 if (ND->isThisDeclarationADefinition() &&
478 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
479 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000480
481 return false;
482}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000483
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000484bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
485 if (VisitDeclaratorDecl(D))
486 return true;
487
488 if (Expr *BitWidth = D->getBitWidth())
489 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
490
491 return false;
492}
493
494bool CursorVisitor::VisitVarDecl(VarDecl *D) {
495 if (VisitDeclaratorDecl(D))
496 return true;
497
498 if (Expr *Init = D->getInit())
499 return Visit(MakeCXCursor(Init, StmtParent, TU));
500
501 return false;
502}
503
504bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
505 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
506 // At the moment, we don't have information about locations in the return
507 // type.
508 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
509 PEnd = ND->param_end();
510 P != PEnd; ++P) {
511 if (Visit(MakeCXCursor(*P, TU)))
512 return true;
513 }
514
515 if (ND->isThisDeclarationADefinition() &&
516 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
517 return true;
518
519 return false;
520}
521
Douglas Gregora59e3902010-01-21 23:27:09 +0000522bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
523 return VisitDeclContext(D);
524}
525
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000527 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
528 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000529 return true;
530
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000531 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
532 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
533 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000534 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000535 return true;
536
Douglas Gregora59e3902010-01-21 23:27:09 +0000537 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000538}
539
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000540bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
541 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
542 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
543 E = PID->protocol_end(); I != E; ++I, ++PL)
544 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
545 return true;
546
547 return VisitObjCContainerDecl(PID);
548}
549
Douglas Gregorb1373d02010-01-20 20:59:29 +0000550bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000551 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000552 if (D->getSuperClass() &&
553 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000554 D->getSuperClassLoc(),
555 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000556 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000557
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000558 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
559 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
560 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000561 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000562 return true;
563
Douglas Gregora59e3902010-01-21 23:27:09 +0000564 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000565}
566
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000567bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
568 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000569}
570
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000571bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
572 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
573 D->getLocation(), TU)))
574 return true;
575
576 return VisitObjCImplDecl(D);
577}
578
579bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
580#if 0
581 // Issue callbacks for super class.
582 // FIXME: No source location information!
583 if (D->getSuperClass() &&
584 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
585 D->getSuperClassLoc(),
586 TU)))
587 return true;
588#endif
589
590 return VisitObjCImplDecl(D);
591}
592
593bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
594 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
595 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
596 E = D->protocol_end();
597 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000598 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000599 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000600
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000601 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000602}
603
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000604bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
605 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
606 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
607 return true;
608
609 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000610}
611
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000612bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
613 ASTContext &Context = TU->getASTContext();
614
615 // Some builtin types (such as Objective-C's "id", "sel", and
616 // "Class") have associated declarations. Create cursors for those.
617 QualType VisitType;
618 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
619 case BuiltinType::Void:
620 case BuiltinType::Bool:
621 case BuiltinType::Char_U:
622 case BuiltinType::UChar:
623 case BuiltinType::Char16:
624 case BuiltinType::Char32:
625 case BuiltinType::UShort:
626 case BuiltinType::UInt:
627 case BuiltinType::ULong:
628 case BuiltinType::ULongLong:
629 case BuiltinType::UInt128:
630 case BuiltinType::Char_S:
631 case BuiltinType::SChar:
632 case BuiltinType::WChar:
633 case BuiltinType::Short:
634 case BuiltinType::Int:
635 case BuiltinType::Long:
636 case BuiltinType::LongLong:
637 case BuiltinType::Int128:
638 case BuiltinType::Float:
639 case BuiltinType::Double:
640 case BuiltinType::LongDouble:
641 case BuiltinType::NullPtr:
642 case BuiltinType::Overload:
643 case BuiltinType::Dependent:
644 break;
645
646 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
647 break;
648
649 case BuiltinType::ObjCId:
650 VisitType = Context.getObjCIdType();
651 break;
652
653 case BuiltinType::ObjCClass:
654 VisitType = Context.getObjCClassType();
655 break;
656
657 case BuiltinType::ObjCSel:
658 VisitType = Context.getObjCSelType();
659 break;
660 }
661
662 if (!VisitType.isNull()) {
663 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
664 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
665 TU));
666 }
667
668 return false;
669}
670
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000671bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
672 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
673}
674
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000675bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
676 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
677}
678
679bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
680 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
681}
682
683bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
684 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
685 return true;
686
687 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
688 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
689 TU)))
690 return true;
691 }
692
693 return false;
694}
695
696bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
697 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
698 return true;
699
700 if (TL.hasProtocolsAsWritten()) {
701 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
702 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
703 TL.getProtocolLoc(I),
704 TU)))
705 return true;
706 }
707 }
708
709 return false;
710}
711
712bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
713 return Visit(TL.getPointeeLoc());
714}
715
716bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
717 return Visit(TL.getPointeeLoc());
718}
719
720bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
721 return Visit(TL.getPointeeLoc());
722}
723
724bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
725 return Visit(TL.getPointeeLoc());
726}
727
728bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
729 return Visit(TL.getPointeeLoc());
730}
731
732bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
733 if (Visit(TL.getResultLoc()))
734 return true;
735
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000736 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
737 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
738 return true;
739
740 return false;
741}
742
743bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
744 if (Visit(TL.getElementLoc()))
745 return true;
746
747 if (Expr *Size = TL.getSizeExpr())
748 return Visit(MakeCXCursor(Size, StmtParent, TU));
749
750 return false;
751}
752
Douglas Gregor2332c112010-01-21 20:48:56 +0000753bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
754 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
755}
756
757bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
758 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
759 return Visit(TSInfo->getTypeLoc());
760
761 return false;
762}
763
Douglas Gregora59e3902010-01-21 23:27:09 +0000764bool CursorVisitor::VisitStmt(Stmt *S) {
765 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
766 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000767 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000768 return true;
769 }
770
771 return false;
772}
773
774bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
775 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
776 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000777 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000778 return true;
779 }
780
781 return false;
782}
783
Douglas Gregorf5bab412010-01-22 01:00:11 +0000784bool CursorVisitor::VisitIfStmt(IfStmt *S) {
785 if (VarDecl *Var = S->getConditionVariable()) {
786 if (Visit(MakeCXCursor(Var, TU)))
787 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000788 }
Douglas Gregorf5bab412010-01-22 01:00:11 +0000789
Douglas Gregor263b47b2010-01-25 16:12:32 +0000790 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
791 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000792 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
793 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000794 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
795 return true;
796
797 return false;
798}
799
800bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
801 if (VarDecl *Var = S->getConditionVariable()) {
802 if (Visit(MakeCXCursor(Var, TU)))
803 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000804 }
805
806 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
807 return true;
808 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
809 return true;
810
811 return false;
812}
813
814bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
815 if (VarDecl *Var = S->getConditionVariable()) {
816 if (Visit(MakeCXCursor(Var, TU)))
817 return true;
818 }
819
820 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
821 return true;
822 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000823 return true;
824
Douglas Gregor263b47b2010-01-25 16:12:32 +0000825 return false;
826}
827
828bool CursorVisitor::VisitForStmt(ForStmt *S) {
829 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
830 return true;
831 if (VarDecl *Var = S->getConditionVariable()) {
832 if (Visit(MakeCXCursor(Var, TU)))
833 return true;
834 }
835
836 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
837 return true;
838 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
839 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000840 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
841 return true;
842
843 return false;
844}
845
Douglas Gregor336fd812010-01-23 00:40:08 +0000846bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
847 if (E->isArgumentType()) {
848 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
849 return Visit(TSInfo->getTypeLoc());
850
851 return false;
852 }
853
854 return VisitExpr(E);
855}
856
857bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
858 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
859 if (Visit(TSInfo->getTypeLoc()))
860 return true;
861
862 return VisitCastExpr(E);
863}
864
865bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
866 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
867 if (Visit(TSInfo->getTypeLoc()))
868 return true;
869
870 return VisitExpr(E);
871}
872
Daniel Dunbar140fce22010-01-12 02:34:07 +0000873CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000874 CXString Str;
875 if (DupString) {
876 Str.Spelling = strdup(String);
877 Str.MustFreeString = 1;
878 } else {
879 Str.Spelling = String;
880 Str.MustFreeString = 0;
881 }
882 return Str;
883}
884
Douglas Gregorfc8ea232010-01-26 17:06:03 +0000885CXString CIndexer::createCXString(llvm::StringRef String, bool DupString) {
886 CXString Result;
887 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
888 char *Spelling = (char *)malloc(String.size() + 1);
889 memmove(Spelling, String.data(), String.size());
890 Spelling[String.size()] = 0;
891 Result.Spelling = Spelling;
892 Result.MustFreeString = 1;
893 } else {
894 Result.Spelling = String.data();
895 Result.MustFreeString = 0;
896 }
897 return Result;
898}
899
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000900extern "C" {
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000901CXIndex clang_createIndex(int excludeDeclarationsFromPCH) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000902 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000903 if (excludeDeclarationsFromPCH)
904 CIdxr->setOnlyLocalDecls();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000905 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000906}
907
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000908void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000909 if (CIdx)
910 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000911}
912
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000913void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000914 if (CIdx) {
915 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
916 CXXIdx->setUseExternalASTGeneration(value);
917 }
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000918}
919
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000920CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000921 const char *ast_filename,
922 CXDiagnosticCallback diag_callback,
923 CXClientData diag_client_data) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000924 if (!CIdx)
925 return 0;
926
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000927 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000928
Douglas Gregor5352ac02010-01-28 00:27:43 +0000929 // Configure the diagnostics.
930 DiagnosticOptions DiagOpts;
931 llvm::OwningPtr<Diagnostic> Diags;
932 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
933 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
934 Diags->setClient(&DiagClient);
935
936 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000937 CXXIdx->getOnlyLocalDecls(),
938 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000939}
940
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000941CXTranslationUnit
942clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
943 const char *source_filename,
944 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000945 const char **command_line_args,
946 unsigned num_unsaved_files,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000947 struct CXUnsavedFile *unsaved_files,
948 CXDiagnosticCallback diag_callback,
949 CXClientData diag_client_data) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +0000950 if (!CIdx)
951 return 0;
952
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000953 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
954
Douglas Gregor5352ac02010-01-28 00:27:43 +0000955 // Configure the diagnostics.
956 DiagnosticOptions DiagOpts;
957 llvm::OwningPtr<Diagnostic> Diags;
958 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
959 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
960 Diags->setClient(&DiagClient);
961
Douglas Gregor4db64a42010-01-23 00:14:00 +0000962 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
963 for (unsigned I = 0; I != num_unsaved_files; ++I) {
964 const llvm::MemoryBuffer *Buffer
965 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
966 unsaved_files[I].Contents + unsaved_files[I].Length,
967 unsaved_files[I].Filename);
968 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
969 Buffer));
970 }
971
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000972 if (!CXXIdx->getUseExternalASTGeneration()) {
973 llvm::SmallVector<const char *, 16> Args;
974
975 // The 'source_filename' argument is optional. If the caller does not
976 // specify it then it is assumed that the source file is specified
977 // in the actual argument list.
978 if (source_filename)
979 Args.push_back(source_filename);
980 Args.insert(Args.end(), command_line_args,
981 command_line_args + num_command_line_args);
982
Douglas Gregor5352ac02010-01-28 00:27:43 +0000983 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000984
Ted Kremenek29b72842010-01-07 22:49:05 +0000985#ifdef USE_CRASHTRACER
986 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000987#endif
988
Daniel Dunbar94220972009-12-05 02:17:18 +0000989 llvm::OwningPtr<ASTUnit> Unit(
990 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor5352ac02010-01-28 00:27:43 +0000991 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +0000992 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000993 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +0000994 /* UseBumpAllocator = */ true,
995 RemappedFiles.data(),
996 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +0000997
Daniel Dunbar94220972009-12-05 02:17:18 +0000998 // FIXME: Until we have broader testing, just drop the entire AST if we
999 // encountered an error.
Douglas Gregor5352ac02010-01-28 00:27:43 +00001000 if (NumErrors != Diags->getNumErrors())
Daniel Dunbar94220972009-12-05 02:17:18 +00001001 return 0;
1002
1003 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +00001004 }
1005
Ted Kremenek139ba862009-10-22 00:03:57 +00001006 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001007 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001008
Ted Kremenek139ba862009-10-22 00:03:57 +00001009 // First add the complete path to the 'clang' executable.
1010 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001011 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001012
Ted Kremenek139ba862009-10-22 00:03:57 +00001013 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001014 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001015
Ted Kremenek139ba862009-10-22 00:03:57 +00001016 // The 'source_filename' argument is optional. If the caller does not
1017 // specify it then it is assumed that the source file is specified
1018 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001019 if (source_filename)
1020 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001021
Steve Naroff37b5ac22009-10-15 20:50:09 +00001022 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001023 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +00001024 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +00001025 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001026
Douglas Gregor4db64a42010-01-23 00:14:00 +00001027 // Remap any unsaved files to temporary files.
1028 std::vector<llvm::sys::Path> TemporaryFiles;
1029 std::vector<std::string> RemapArgs;
1030 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1031 return 0;
1032
1033 // The pointers into the elements of RemapArgs are stable because we
1034 // won't be adding anything to RemapArgs after this point.
1035 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1036 argv.push_back(RemapArgs[i].c_str());
1037
Ted Kremenek139ba862009-10-22 00:03:57 +00001038 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1039 for (int i = 0; i < num_command_line_args; ++i)
1040 if (const char *arg = command_line_args[i]) {
1041 if (strcmp(arg, "-o") == 0) {
1042 ++i; // Also skip the matching argument.
1043 continue;
1044 }
1045 if (strcmp(arg, "-emit-ast") == 0 ||
1046 strcmp(arg, "-c") == 0 ||
1047 strcmp(arg, "-fsyntax-only") == 0) {
1048 continue;
1049 }
1050
1051 // Keep the argument.
1052 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001053 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001054
Douglas Gregord93256e2010-01-28 06:00:51 +00001055 // Generate a temporary name for the diagnostics file.
1056 char tmpFileResults[L_tmpnam];
1057 char *tmpResultsFileName = tmpnam(tmpFileResults);
1058 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
1059 TemporaryFiles.push_back(DiagnosticsFile);
1060 argv.push_back("-fdiagnostics-binary");
1061
Ted Kremenek139ba862009-10-22 00:03:57 +00001062 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001063 argv.push_back(NULL);
1064
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001065 // Invoke 'clang'.
1066 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1067 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001068 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001069 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1070 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001071 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001072 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001073 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001074
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001075 if (!ErrMsg.empty()) {
1076 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001077 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001078 I != E; ++I) {
1079 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001080 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001081 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001082 }
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001083
1084 Diags->Report(diag::err_fe_clang) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001085 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001086
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001087 // FIXME: Parse the (redirected) standard error to emit diagnostics.
1088
Douglas Gregor5352ac02010-01-28 00:27:43 +00001089 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001090 CXXIdx->getOnlyLocalDecls(),
1091 /* UseBumpAllocator = */ true,
1092 RemappedFiles.data(),
1093 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001094 if (ATU)
1095 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001096
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00001097 // FIXME: Currently we don't report diagnostics on invalid ASTs.
1098 if (ATU)
1099 ReportSerializedDiagnostics(DiagnosticsFile, *Diags,
1100 num_unsaved_files, unsaved_files,
1101 ATU->getASTContext().getLangOptions());
Douglas Gregord93256e2010-01-28 06:00:51 +00001102
Douglas Gregor4db64a42010-01-23 00:14:00 +00001103 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1104 TemporaryFiles[i].eraseFromDisk();
1105
Steve Naroffe19944c2009-10-15 22:23:48 +00001106 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001107}
1108
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001109void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001110 if (CTUnit)
1111 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001112}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001113
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001114CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001115 if (!CTUnit)
1116 return CIndexer::createCXString("");
1117
Steve Naroff77accc12009-09-03 18:19:54 +00001118 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001119 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1120 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001121}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001122
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001123CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001124 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001125 return Result;
1126}
1127
Ted Kremenekfb480492010-01-13 21:46:36 +00001128} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001129
Ted Kremenekfb480492010-01-13 21:46:36 +00001130//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001131// CXSourceLocation and CXSourceRange Operations.
1132//===----------------------------------------------------------------------===//
1133
Douglas Gregorb9790342010-01-22 21:44:22 +00001134extern "C" {
1135CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001136 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001137 return Result;
1138}
1139
1140unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001141 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1142 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1143 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001144}
1145
1146CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1147 CXFile file,
1148 unsigned line,
1149 unsigned column) {
1150 if (!tu)
1151 return clang_getNullLocation();
1152
1153 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1154 SourceLocation SLoc
1155 = CXXUnit->getSourceManager().getLocation(
1156 static_cast<const FileEntry *>(file),
1157 line, column);
1158
Ted Kremeneka297de22010-01-25 22:34:44 +00001159 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc, false);
Douglas Gregorb9790342010-01-22 21:44:22 +00001160}
1161
Douglas Gregor5352ac02010-01-28 00:27:43 +00001162CXSourceRange clang_getNullRange() {
1163 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1164 return Result;
1165}
Douglas Gregorb9790342010-01-22 21:44:22 +00001166
Douglas Gregor5352ac02010-01-28 00:27:43 +00001167CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1168 if (begin.ptr_data[0] != end.ptr_data[0] ||
1169 begin.ptr_data[1] != end.ptr_data[1])
1170 return clang_getNullRange();
1171
1172 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1173 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001174 return Result;
1175}
1176
Douglas Gregor46766dc2010-01-26 19:19:08 +00001177void clang_getInstantiationLocation(CXSourceLocation location,
1178 CXFile *file,
1179 unsigned *line,
1180 unsigned *column,
1181 unsigned *offset) {
Ted Kremeneka297de22010-01-25 22:34:44 +00001182 cxloc::CXSourceLocationPtr Ptr
Douglas Gregor5352ac02010-01-28 00:27:43 +00001183 = cxloc::CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001184 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1185
Douglas Gregor46766dc2010-01-26 19:19:08 +00001186 if (!Ptr.getPointer() || Loc.isInvalid()) {
1187 if (file)
1188 *file = 0;
1189 if (line)
1190 *line = 0;
1191 if (column)
1192 *column = 0;
1193 if (offset)
1194 *offset = 0;
1195 return;
1196 }
1197
Douglas Gregor1db19de2010-01-19 21:36:55 +00001198 // FIXME: This is largely copy-paste from
1199 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
1200 // what we want the two routines should be refactored.
Douglas Gregor5352ac02010-01-28 00:27:43 +00001201 const SourceManager &SM = *Ptr.getPointer();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001202 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1203
1204 if (Ptr.getInt()) {
1205 // We want the last character in this location, so we will adjust
1206 // the instantiation location accordingly.
1207
1208 // If the location is from a macro instantiation, get the end of
1209 // the instantiation range.
1210 if (Loc.isMacroID())
1211 InstLoc = SM.getInstantiationRange(Loc).second;
1212
1213 // Measure the length token we're pointing at, so we can adjust
1214 // the physical location in the file to point at the last
1215 // character.
1216 // FIXME: This won't cope with trigraphs or escaped newlines
1217 // well. For that, we actually need a preprocessor, which isn't
1218 // currently available here. Eventually, we'll switch the pointer
1219 // data of CXSourceLocation/CXSourceRange to a translation unit
1220 // (CXXUnit), so that the preprocessor will be available here. At
1221 // that point, we can use Preprocessor::getLocForEndOfToken().
1222 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
Douglas Gregor5352ac02010-01-28 00:27:43 +00001223 *static_cast<LangOptions *>(location.ptr_data[1]));
Douglas Gregor1db19de2010-01-19 21:36:55 +00001224 if (Length > 0)
1225 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
1226 }
1227
1228 if (file)
1229 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1230 if (line)
1231 *line = SM.getInstantiationLineNumber(InstLoc);
1232 if (column)
1233 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001234 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001235 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001236}
1237
Douglas Gregor1db19de2010-01-19 21:36:55 +00001238CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001239 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1240 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001241 return Result;
1242}
1243
1244CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001245 cxloc::CXSourceLocationPtr Ptr;
1246 Ptr.setPointer(static_cast<SourceManager *>(range.ptr_data[0]));
Douglas Gregor1db19de2010-01-19 21:36:55 +00001247 Ptr.setInt(true);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001248 CXSourceLocation Result = { { Ptr.getOpaqueValue(), range.ptr_data[1] },
1249 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()) {
1471 SourceRange RegionOfInterest(SLoc,
1472 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1473
1474 // FIXME: Would be great to have a "hint" cursor, then walk from that
1475 // hint cursor upward until we find a cursor whose source range encloses
1476 // the region of interest, rather than starting from the translation unit.
1477 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1478 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1479 Decl::MaxPCHLevel, RegionOfInterest);
1480 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001481 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001482 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001483}
1484
Ted Kremenek73885552009-11-17 19:28:59 +00001485CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001486 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001487}
1488
1489unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001490 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001491}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001492
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001493unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001494 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1495}
1496
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001497unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001498 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1499}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001500
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001501unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001502 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1503}
1504
Douglas Gregor97b98722010-01-19 23:20:36 +00001505unsigned clang_isExpression(enum CXCursorKind K) {
1506 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1507}
1508
1509unsigned clang_isStatement(enum CXCursorKind K) {
1510 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1511}
1512
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001513unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1514 return K == CXCursor_TranslationUnit;
1515}
1516
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001517CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001518 return C.kind;
1519}
1520
Douglas Gregor98258af2010-01-18 22:46:11 +00001521CXSourceLocation clang_getCursorLocation(CXCursor C) {
1522 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001523 switch (C.kind) {
1524 case CXCursor_ObjCSuperClassRef: {
1525 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1526 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001527 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001528 }
1529
1530 case CXCursor_ObjCProtocolRef: {
1531 std::pair<ObjCProtocolDecl *, SourceLocation> P
1532 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001533 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001534 }
1535
1536 case CXCursor_ObjCClassRef: {
1537 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1538 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001539 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001540 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001541
1542 case CXCursor_TypeRef: {
1543 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001544 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001545 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001546
Douglas Gregorf46034a2010-01-18 23:41:10 +00001547 default:
1548 // FIXME: Need a way to enumerate all non-reference cases.
1549 llvm_unreachable("Missed a reference kind");
1550 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001551 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001552
1553 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001554 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001555 getLocationFromExpr(getCursorExpr(C)));
1556
Douglas Gregor5352ac02010-01-28 00:27:43 +00001557 if (!getCursorDecl(C))
1558 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001559
Douglas Gregorf46034a2010-01-18 23:41:10 +00001560 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001561 SourceLocation Loc = D->getLocation();
1562 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1563 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001564 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001565}
Douglas Gregora7bde202010-01-19 00:34:46 +00001566
1567CXSourceRange clang_getCursorExtent(CXCursor C) {
1568 if (clang_isReference(C.kind)) {
1569 switch (C.kind) {
1570 case CXCursor_ObjCSuperClassRef: {
1571 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1572 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001573 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001574 }
1575
1576 case CXCursor_ObjCProtocolRef: {
1577 std::pair<ObjCProtocolDecl *, SourceLocation> P
1578 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001579 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001580 }
1581
1582 case CXCursor_ObjCClassRef: {
1583 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1584 = getCursorObjCClassRef(C);
1585
Ted Kremeneka297de22010-01-25 22:34:44 +00001586 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001587 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001588
1589 case CXCursor_TypeRef: {
1590 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001591 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001592 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001593
Douglas Gregora7bde202010-01-19 00:34:46 +00001594 default:
1595 // FIXME: Need a way to enumerate all non-reference cases.
1596 llvm_unreachable("Missed a reference kind");
1597 }
1598 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001599
1600 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001601 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001602 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001603
1604 if (clang_isStatement(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001605 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001606 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001607
Douglas Gregor5352ac02010-01-28 00:27:43 +00001608 if (!getCursorDecl(C))
1609 return clang_getNullRange();
Douglas Gregora7bde202010-01-19 00:34:46 +00001610
1611 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001612 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001613}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001614
1615CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001616 if (clang_isInvalid(C.kind))
1617 return clang_getNullCursor();
1618
1619 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001620 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001621 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001622
Douglas Gregor97b98722010-01-19 23:20:36 +00001623 if (clang_isExpression(C.kind)) {
1624 Decl *D = getDeclFromExpr(getCursorExpr(C));
1625 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001626 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001627 return clang_getNullCursor();
1628 }
1629
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001630 if (!clang_isReference(C.kind))
1631 return clang_getNullCursor();
1632
1633 switch (C.kind) {
1634 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001635 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001636
1637 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001638 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001639
1640 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001641 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001642
1643 case CXCursor_TypeRef:
1644 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001645
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001646 default:
1647 // We would prefer to enumerate all non-reference cursor kinds here.
1648 llvm_unreachable("Unhandled reference cursor kind");
1649 break;
1650 }
1651 }
1652
1653 return clang_getNullCursor();
1654}
1655
Douglas Gregorb6998662010-01-19 19:34:47 +00001656CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001657 if (clang_isInvalid(C.kind))
1658 return clang_getNullCursor();
1659
1660 ASTUnit *CXXUnit = getCursorASTUnit(C);
1661
Douglas Gregorb6998662010-01-19 19:34:47 +00001662 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001663 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001664 C = clang_getCursorReferenced(C);
1665 WasReference = true;
1666 }
1667
1668 if (!clang_isDeclaration(C.kind))
1669 return clang_getNullCursor();
1670
1671 Decl *D = getCursorDecl(C);
1672 if (!D)
1673 return clang_getNullCursor();
1674
1675 switch (D->getKind()) {
1676 // Declaration kinds that don't really separate the notions of
1677 // declaration and definition.
1678 case Decl::Namespace:
1679 case Decl::Typedef:
1680 case Decl::TemplateTypeParm:
1681 case Decl::EnumConstant:
1682 case Decl::Field:
1683 case Decl::ObjCIvar:
1684 case Decl::ObjCAtDefsField:
1685 case Decl::ImplicitParam:
1686 case Decl::ParmVar:
1687 case Decl::NonTypeTemplateParm:
1688 case Decl::TemplateTemplateParm:
1689 case Decl::ObjCCategoryImpl:
1690 case Decl::ObjCImplementation:
1691 case Decl::LinkageSpec:
1692 case Decl::ObjCPropertyImpl:
1693 case Decl::FileScopeAsm:
1694 case Decl::StaticAssert:
1695 case Decl::Block:
1696 return C;
1697
1698 // Declaration kinds that don't make any sense here, but are
1699 // nonetheless harmless.
1700 case Decl::TranslationUnit:
1701 case Decl::Template:
1702 case Decl::ObjCContainer:
1703 break;
1704
1705 // Declaration kinds for which the definition is not resolvable.
1706 case Decl::UnresolvedUsingTypename:
1707 case Decl::UnresolvedUsingValue:
1708 break;
1709
1710 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001711 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1712 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001713
1714 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001715 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001716
1717 case Decl::Enum:
1718 case Decl::Record:
1719 case Decl::CXXRecord:
1720 case Decl::ClassTemplateSpecialization:
1721 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00001722 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001723 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001724 return clang_getNullCursor();
1725
1726 case Decl::Function:
1727 case Decl::CXXMethod:
1728 case Decl::CXXConstructor:
1729 case Decl::CXXDestructor:
1730 case Decl::CXXConversion: {
1731 const FunctionDecl *Def = 0;
1732 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001733 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001734 return clang_getNullCursor();
1735 }
1736
1737 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00001738 // Ask the variable if it has a definition.
1739 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
1740 return MakeCXCursor(Def, CXXUnit);
1741 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00001742 }
1743
1744 case Decl::FunctionTemplate: {
1745 const FunctionDecl *Def = 0;
1746 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001747 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001748 return clang_getNullCursor();
1749 }
1750
1751 case Decl::ClassTemplate: {
1752 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00001753 ->getDefinition())
Douglas Gregorb6998662010-01-19 19:34:47 +00001754 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001755 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1756 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001757 return clang_getNullCursor();
1758 }
1759
1760 case Decl::Using: {
1761 UsingDecl *Using = cast<UsingDecl>(D);
1762 CXCursor Def = clang_getNullCursor();
1763 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1764 SEnd = Using->shadow_end();
1765 S != SEnd; ++S) {
1766 if (Def != clang_getNullCursor()) {
1767 // FIXME: We have no way to return multiple results.
1768 return clang_getNullCursor();
1769 }
1770
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001771 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1772 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001773 }
1774
1775 return Def;
1776 }
1777
1778 case Decl::UsingShadow:
1779 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001780 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1781 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001782
1783 case Decl::ObjCMethod: {
1784 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1785 if (Method->isThisDeclarationADefinition())
1786 return C;
1787
1788 // Dig out the method definition in the associated
1789 // @implementation, if we have it.
1790 // FIXME: The ASTs should make finding the definition easier.
1791 if (ObjCInterfaceDecl *Class
1792 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1793 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1794 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1795 Method->isInstanceMethod()))
1796 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001797 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001798
1799 return clang_getNullCursor();
1800 }
1801
1802 case Decl::ObjCCategory:
1803 if (ObjCCategoryImplDecl *Impl
1804 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001805 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001806 return clang_getNullCursor();
1807
1808 case Decl::ObjCProtocol:
1809 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1810 return C;
1811 return clang_getNullCursor();
1812
1813 case Decl::ObjCInterface:
1814 // There are two notions of a "definition" for an Objective-C
1815 // class: the interface and its implementation. When we resolved a
1816 // reference to an Objective-C class, produce the @interface as
1817 // the definition; when we were provided with the interface,
1818 // produce the @implementation as the definition.
1819 if (WasReference) {
1820 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1821 return C;
1822 } else if (ObjCImplementationDecl *Impl
1823 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001824 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001825 return clang_getNullCursor();
1826
1827 case Decl::ObjCProperty:
1828 // FIXME: We don't really know where to find the
1829 // ObjCPropertyImplDecls that implement this property.
1830 return clang_getNullCursor();
1831
1832 case Decl::ObjCCompatibleAlias:
1833 if (ObjCInterfaceDecl *Class
1834 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1835 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001836 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001837
1838 return clang_getNullCursor();
1839
1840 case Decl::ObjCForwardProtocol: {
1841 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1842 if (Forward->protocol_size() == 1)
1843 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001844 MakeCXCursor(*Forward->protocol_begin(),
1845 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001846
1847 // FIXME: Cannot return multiple definitions.
1848 return clang_getNullCursor();
1849 }
1850
1851 case Decl::ObjCClass: {
1852 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1853 if (Class->size() == 1) {
1854 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1855 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001856 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001857 return clang_getNullCursor();
1858 }
1859
1860 // FIXME: Cannot return multiple definitions.
1861 return clang_getNullCursor();
1862 }
1863
1864 case Decl::Friend:
1865 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001866 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001867 return clang_getNullCursor();
1868
1869 case Decl::FriendTemplate:
1870 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001871 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001872 return clang_getNullCursor();
1873 }
1874
1875 return clang_getNullCursor();
1876}
1877
1878unsigned clang_isCursorDefinition(CXCursor C) {
1879 if (!clang_isDeclaration(C.kind))
1880 return 0;
1881
1882 return clang_getCursorDefinition(C) == C;
1883}
1884
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001885void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001886 const char **startBuf,
1887 const char **endBuf,
1888 unsigned *startLine,
1889 unsigned *startColumn,
1890 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001891 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001892 assert(getCursorDecl(C) && "CXCursor has null decl");
1893 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001894 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1895 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001896
Steve Naroff4ade6d62009-09-23 17:52:52 +00001897 SourceManager &SM = FD->getASTContext().getSourceManager();
1898 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1899 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1900 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1901 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1902 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1903 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1904}
Ted Kremenekfb480492010-01-13 21:46:36 +00001905
1906} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001907
Ted Kremenekfb480492010-01-13 21:46:36 +00001908//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001909// Token-based Operations.
1910//===----------------------------------------------------------------------===//
1911
1912/* CXToken layout:
1913 * int_data[0]: a CXTokenKind
1914 * int_data[1]: starting token location
1915 * int_data[2]: token length
1916 * int_data[3]: reserved
1917 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
1918 * otherwise unused.
1919 */
1920extern "C" {
1921
1922CXTokenKind clang_getTokenKind(CXToken CXTok) {
1923 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1924}
1925
1926CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1927 switch (clang_getTokenKind(CXTok)) {
1928 case CXToken_Identifier:
1929 case CXToken_Keyword:
1930 // We know we have an IdentifierInfo*, so use that.
1931 return CIndexer::createCXString(
1932 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
1933
1934 case CXToken_Literal: {
1935 // We have stashed the starting pointer in the ptr_data field. Use it.
1936 const char *Text = static_cast<const char *>(CXTok.ptr_data);
1937 return CIndexer::createCXString(llvm::StringRef(Text, CXTok.int_data[2]),
1938 true);
1939 }
1940
1941 case CXToken_Punctuation:
1942 case CXToken_Comment:
1943 break;
1944 }
1945
1946 // We have to find the starting buffer pointer the hard way, by
1947 // deconstructing the source location.
1948 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1949 if (!CXXUnit)
1950 return CIndexer::createCXString("");
1951
1952 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1953 std::pair<FileID, unsigned> LocInfo
1954 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1955 std::pair<const char *,const char *> Buffer
1956 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1957
1958 return CIndexer::createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1959 CXTok.int_data[2]),
1960 true);
1961}
1962
1963CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1964 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1965 if (!CXXUnit)
1966 return clang_getNullLocation();
1967
1968 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1969 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1970}
1971
1972CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1973 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001974 if (!CXXUnit)
1975 return clang_getNullRange();
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001976
1977 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
1978 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1979}
1980
1981void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1982 CXToken **Tokens, unsigned *NumTokens) {
1983 if (Tokens)
1984 *Tokens = 0;
1985 if (NumTokens)
1986 *NumTokens = 0;
1987
1988 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1989 if (!CXXUnit || !Tokens || !NumTokens)
1990 return;
1991
1992 SourceRange R = cxloc::translateSourceRange(Range);
1993 if (R.isInvalid())
1994 return;
1995
1996 SourceManager &SourceMgr = CXXUnit->getSourceManager();
1997 std::pair<FileID, unsigned> BeginLocInfo
1998 = SourceMgr.getDecomposedLoc(R.getBegin());
1999 std::pair<FileID, unsigned> EndLocInfo
2000 = SourceMgr.getDecomposedLoc(R.getEnd());
2001
2002 // Cannot tokenize across files.
2003 if (BeginLocInfo.first != EndLocInfo.first)
2004 return;
2005
2006 // Create a lexer
2007 std::pair<const char *,const char *> Buffer
2008 = SourceMgr.getBufferData(BeginLocInfo.first);
2009 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2010 CXXUnit->getASTContext().getLangOptions(),
2011 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
2012 Lex.SetCommentRetentionState(true);
2013
2014 // Lex tokens until we hit the end of the range.
2015 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
2016 llvm::SmallVector<CXToken, 32> CXTokens;
2017 Token Tok;
2018 do {
2019 // Lex the next token
2020 Lex.LexFromRawLexer(Tok);
2021 if (Tok.is(tok::eof))
2022 break;
2023
2024 // Initialize the CXToken.
2025 CXToken CXTok;
2026
2027 // - Common fields
2028 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2029 CXTok.int_data[2] = Tok.getLength();
2030 CXTok.int_data[3] = 0;
2031
2032 // - Kind-specific fields
2033 if (Tok.isLiteral()) {
2034 CXTok.int_data[0] = CXToken_Literal;
2035 CXTok.ptr_data = (void *)Tok.getLiteralData();
2036 } else if (Tok.is(tok::identifier)) {
2037 // Lookup the identifier to determine whether we have a
2038 std::pair<FileID, unsigned> LocInfo
2039 = SourceMgr.getDecomposedLoc(Tok.getLocation());
2040 const char *StartPos
2041 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
2042 LocInfo.second;
2043 IdentifierInfo *II
2044 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2045 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2046 CXToken_Identifier
2047 : CXToken_Keyword;
2048 CXTok.ptr_data = II;
2049 } else if (Tok.is(tok::comment)) {
2050 CXTok.int_data[0] = CXToken_Comment;
2051 CXTok.ptr_data = 0;
2052 } else {
2053 CXTok.int_data[0] = CXToken_Punctuation;
2054 CXTok.ptr_data = 0;
2055 }
2056 CXTokens.push_back(CXTok);
2057 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2058
2059 if (CXTokens.empty())
2060 return;
2061
2062 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2063 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2064 *NumTokens = CXTokens.size();
2065}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002066
2067typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2068
2069enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2070 CXCursor parent,
2071 CXClientData client_data) {
2072 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2073
2074 // We only annotate the locations of declarations, simple
2075 // references, and expressions which directly reference something.
2076 CXCursorKind Kind = clang_getCursorKind(cursor);
2077 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2078 // Okay: We can annotate the location of this declaration with the
2079 // declaration or reference
2080 } else if (clang_isExpression(cursor.kind)) {
2081 if (Kind != CXCursor_DeclRefExpr &&
2082 Kind != CXCursor_MemberRefExpr &&
2083 Kind != CXCursor_ObjCMessageExpr)
2084 return CXChildVisit_Recurse;
2085
2086 CXCursor Referenced = clang_getCursorReferenced(cursor);
2087 if (Referenced == cursor || Referenced == clang_getNullCursor())
2088 return CXChildVisit_Recurse;
2089
2090 // Okay: we can annotate the location of this expression
2091 } else {
2092 // Nothing to annotate
2093 return CXChildVisit_Recurse;
2094 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002095
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002096 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2097 (*Data)[Loc.int_data] = cursor;
2098 return CXChildVisit_Recurse;
2099}
2100
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002101void clang_annotateTokens(CXTranslationUnit TU,
2102 CXToken *Tokens, unsigned NumTokens,
2103 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002104 if (NumTokens == 0)
2105 return;
2106
2107 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002108 for (unsigned I = 0; I != NumTokens; ++I)
2109 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002110
2111 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2112 if (!CXXUnit || !Tokens)
2113 return;
2114
2115 // Annotate all of the source locations in the region of interest that map
2116 SourceRange RegionOfInterest;
2117 RegionOfInterest.setBegin(
2118 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2119 SourceLocation End
2120 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2121 Tokens[NumTokens - 1]));
2122 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End,
2123 1));
2124 // FIXME: Would be great to have a "hint" cursor, then walk from that
2125 // hint cursor upward until we find a cursor whose source range encloses
2126 // the region of interest, rather than starting from the translation unit.
2127 AnnotateTokensData Annotated;
2128 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2129 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2130 Decl::MaxPCHLevel, RegionOfInterest);
2131 AnnotateVis.VisitChildren(Parent);
2132
2133 for (unsigned I = 0; I != NumTokens; ++I) {
2134 // Determine whether we saw a cursor at this token's location.
2135 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2136 if (Pos == Annotated.end())
2137 continue;
2138
2139 Cursors[I] = Pos->second;
2140 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002141}
2142
2143void clang_disposeTokens(CXTranslationUnit TU,
2144 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002145 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002146}
2147
2148} // end: extern "C"
2149
2150//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002151// CXString Operations.
2152//===----------------------------------------------------------------------===//
2153
2154extern "C" {
2155const char *clang_getCString(CXString string) {
2156 return string.Spelling;
2157}
2158
2159void clang_disposeString(CXString string) {
2160 if (string.MustFreeString && string.Spelling)
2161 free((void*)string.Spelling);
2162}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002163
Ted Kremenekfb480492010-01-13 21:46:36 +00002164} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002165
2166//===----------------------------------------------------------------------===//
2167// Misc. utility functions.
2168//===----------------------------------------------------------------------===//
2169
2170extern "C" {
2171
2172const char *clang_getClangVersion() {
Ted Kremeneka18f1b82010-01-23 02:11:34 +00002173 return getClangFullVersion();
Ted Kremenek04bb7162010-01-22 22:44:15 +00002174}
2175
2176} // end: extern "C"
2177