blob: 5e97494dd9b955814156678fefced1c967130672 [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
Douglas Gregord93256e2010-01-28 06:00:51 +00001097 ReportSerializedDiagnostics(DiagnosticsFile, *Diags,
Daniel Dunbar35b84402010-01-30 23:31:40 +00001098 num_unsaved_files, unsaved_files,
1099 ATU->getASTContext().getLangOptions());
Douglas Gregord93256e2010-01-28 06:00:51 +00001100
Douglas Gregor4db64a42010-01-23 00:14:00 +00001101 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1102 TemporaryFiles[i].eraseFromDisk();
1103
Steve Naroffe19944c2009-10-15 22:23:48 +00001104 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001105}
1106
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001107void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001108 if (CTUnit)
1109 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001110}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001111
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001112CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00001113 if (!CTUnit)
1114 return CIndexer::createCXString("");
1115
Steve Naroff77accc12009-09-03 18:19:54 +00001116 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001117 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1118 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001119}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001120
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001121CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001122 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001123 return Result;
1124}
1125
Ted Kremenekfb480492010-01-13 21:46:36 +00001126} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001127
Ted Kremenekfb480492010-01-13 21:46:36 +00001128//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001129// CXSourceLocation and CXSourceRange Operations.
1130//===----------------------------------------------------------------------===//
1131
Douglas Gregorb9790342010-01-22 21:44:22 +00001132extern "C" {
1133CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001134 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001135 return Result;
1136}
1137
1138unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00001139 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1140 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1141 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00001142}
1143
1144CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1145 CXFile file,
1146 unsigned line,
1147 unsigned column) {
1148 if (!tu)
1149 return clang_getNullLocation();
1150
1151 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1152 SourceLocation SLoc
1153 = CXXUnit->getSourceManager().getLocation(
1154 static_cast<const FileEntry *>(file),
1155 line, column);
1156
Ted Kremeneka297de22010-01-25 22:34:44 +00001157 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc, false);
Douglas Gregorb9790342010-01-22 21:44:22 +00001158}
1159
Douglas Gregor5352ac02010-01-28 00:27:43 +00001160CXSourceRange clang_getNullRange() {
1161 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1162 return Result;
1163}
Douglas Gregorb9790342010-01-22 21:44:22 +00001164
Douglas Gregor5352ac02010-01-28 00:27:43 +00001165CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1166 if (begin.ptr_data[0] != end.ptr_data[0] ||
1167 begin.ptr_data[1] != end.ptr_data[1])
1168 return clang_getNullRange();
1169
1170 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1171 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001172 return Result;
1173}
1174
Douglas Gregor46766dc2010-01-26 19:19:08 +00001175void clang_getInstantiationLocation(CXSourceLocation location,
1176 CXFile *file,
1177 unsigned *line,
1178 unsigned *column,
1179 unsigned *offset) {
Ted Kremeneka297de22010-01-25 22:34:44 +00001180 cxloc::CXSourceLocationPtr Ptr
Douglas Gregor5352ac02010-01-28 00:27:43 +00001181 = cxloc::CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001182 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1183
Douglas Gregor46766dc2010-01-26 19:19:08 +00001184 if (!Ptr.getPointer() || Loc.isInvalid()) {
1185 if (file)
1186 *file = 0;
1187 if (line)
1188 *line = 0;
1189 if (column)
1190 *column = 0;
1191 if (offset)
1192 *offset = 0;
1193 return;
1194 }
1195
Douglas Gregor1db19de2010-01-19 21:36:55 +00001196 // FIXME: This is largely copy-paste from
1197 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
1198 // what we want the two routines should be refactored.
Douglas Gregor5352ac02010-01-28 00:27:43 +00001199 const SourceManager &SM = *Ptr.getPointer();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001200 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1201
1202 if (Ptr.getInt()) {
1203 // We want the last character in this location, so we will adjust
1204 // the instantiation location accordingly.
1205
1206 // If the location is from a macro instantiation, get the end of
1207 // the instantiation range.
1208 if (Loc.isMacroID())
1209 InstLoc = SM.getInstantiationRange(Loc).second;
1210
1211 // Measure the length token we're pointing at, so we can adjust
1212 // the physical location in the file to point at the last
1213 // character.
1214 // FIXME: This won't cope with trigraphs or escaped newlines
1215 // well. For that, we actually need a preprocessor, which isn't
1216 // currently available here. Eventually, we'll switch the pointer
1217 // data of CXSourceLocation/CXSourceRange to a translation unit
1218 // (CXXUnit), so that the preprocessor will be available here. At
1219 // that point, we can use Preprocessor::getLocForEndOfToken().
1220 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
Douglas Gregor5352ac02010-01-28 00:27:43 +00001221 *static_cast<LangOptions *>(location.ptr_data[1]));
Douglas Gregor1db19de2010-01-19 21:36:55 +00001222 if (Length > 0)
1223 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
1224 }
1225
1226 if (file)
1227 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1228 if (line)
1229 *line = SM.getInstantiationLineNumber(InstLoc);
1230 if (column)
1231 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001232 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001233 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001234}
1235
Douglas Gregor1db19de2010-01-19 21:36:55 +00001236CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001237 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1238 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001239 return Result;
1240}
1241
1242CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001243 cxloc::CXSourceLocationPtr Ptr;
1244 Ptr.setPointer(static_cast<SourceManager *>(range.ptr_data[0]));
Douglas Gregor1db19de2010-01-19 21:36:55 +00001245 Ptr.setInt(true);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001246 CXSourceLocation Result = { { Ptr.getOpaqueValue(), range.ptr_data[1] },
1247 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001248 return Result;
1249}
1250
Douglas Gregorb9790342010-01-22 21:44:22 +00001251} // end: extern "C"
1252
Douglas Gregor1db19de2010-01-19 21:36:55 +00001253//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001254// CXFile Operations.
1255//===----------------------------------------------------------------------===//
1256
1257extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001258const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001259 if (!SFile)
1260 return 0;
1261
Steve Naroff88145032009-10-27 14:35:18 +00001262 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1263 return FEnt->getName();
1264}
1265
1266time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001267 if (!SFile)
1268 return 0;
1269
Steve Naroff88145032009-10-27 14:35:18 +00001270 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1271 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001272}
Douglas Gregorb9790342010-01-22 21:44:22 +00001273
1274CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1275 if (!tu)
1276 return 0;
1277
1278 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1279
1280 FileManager &FMgr = CXXUnit->getFileManager();
1281 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1282 return const_cast<FileEntry *>(File);
1283}
1284
Ted Kremenekfb480492010-01-13 21:46:36 +00001285} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001286
Ted Kremenekfb480492010-01-13 21:46:36 +00001287//===----------------------------------------------------------------------===//
1288// CXCursor Operations.
1289//===----------------------------------------------------------------------===//
1290
Ted Kremenekfb480492010-01-13 21:46:36 +00001291static Decl *getDeclFromExpr(Stmt *E) {
1292 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1293 return RefExpr->getDecl();
1294 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1295 return ME->getMemberDecl();
1296 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1297 return RE->getDecl();
1298
1299 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1300 return getDeclFromExpr(CE->getCallee());
1301 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1302 return getDeclFromExpr(CE->getSubExpr());
1303 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1304 return OME->getMethodDecl();
1305
1306 return 0;
1307}
1308
1309extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001310
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001311unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001312 CXCursorVisitor visitor,
1313 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001314 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001315
1316 unsigned PCHLevel = Decl::MaxPCHLevel;
1317
1318 // Set the PCHLevel to filter out unwanted decls if requested.
1319 if (CXXUnit->getOnlyLocalDecls()) {
1320 PCHLevel = 0;
1321
1322 // If the main input was an AST, bump the level.
1323 if (CXXUnit->isMainFileAST())
1324 ++PCHLevel;
1325 }
1326
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001327 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001328 return CursorVis.VisitChildren(parent);
1329}
1330
Douglas Gregor78205d42010-01-20 21:45:58 +00001331static CXString getDeclSpelling(Decl *D) {
1332 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1333 if (!ND)
1334 return CIndexer::createCXString("");
1335
1336 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1337 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1338 true);
1339
1340 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1341 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1342 // and returns different names. NamedDecl returns the class name and
1343 // ObjCCategoryImplDecl returns the category name.
1344 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1345
1346 if (ND->getIdentifier())
1347 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1348
1349 return CIndexer::createCXString("");
1350}
1351
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001352CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001353 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001354 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001355
Steve Narofff334b4e2009-09-02 18:26:48 +00001356 if (clang_isReference(C.kind)) {
1357 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001358 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001359 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1360 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001361 }
1362 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001363 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1364 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001365 }
1366 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001367 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001368 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001369 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001370 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001371 case CXCursor_TypeRef: {
1372 TypeDecl *Type = getCursorTypeRef(C).first;
1373 assert(Type && "Missing type decl");
1374
1375 return CIndexer::createCXString(
1376 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1377 true);
1378 }
1379
Daniel Dunbaracca7252009-11-30 20:42:49 +00001380 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001381 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001382 }
1383 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001384
1385 if (clang_isExpression(C.kind)) {
1386 Decl *D = getDeclFromExpr(getCursorExpr(C));
1387 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001388 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001389 return CIndexer::createCXString("");
1390 }
1391
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001392 if (clang_isDeclaration(C.kind))
1393 return getDeclSpelling(getCursorDecl(C));
1394
1395 return CIndexer::createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001396}
1397
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001398const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001399 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001400 case CXCursor_FunctionDecl: return "FunctionDecl";
1401 case CXCursor_TypedefDecl: return "TypedefDecl";
1402 case CXCursor_EnumDecl: return "EnumDecl";
1403 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1404 case CXCursor_StructDecl: return "StructDecl";
1405 case CXCursor_UnionDecl: return "UnionDecl";
1406 case CXCursor_ClassDecl: return "ClassDecl";
1407 case CXCursor_FieldDecl: return "FieldDecl";
1408 case CXCursor_VarDecl: return "VarDecl";
1409 case CXCursor_ParmDecl: return "ParmDecl";
1410 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1411 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1412 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1413 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1414 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1415 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1416 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001417 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1418 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001419 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001420 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1421 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1422 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001423 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001424 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1425 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1426 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1427 case CXCursor_CallExpr: return "CallExpr";
1428 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1429 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001430 case CXCursor_InvalidFile: return "InvalidFile";
1431 case CXCursor_NoDeclFound: return "NoDeclFound";
1432 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001433 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001434 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001435
1436 llvm_unreachable("Unhandled CXCursorKind");
1437 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001438}
Steve Naroff89922f82009-08-31 00:59:03 +00001439
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001440enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1441 CXCursor parent,
1442 CXClientData client_data) {
1443 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1444 *BestCursor = cursor;
1445 return CXChildVisit_Recurse;
1446}
1447
Douglas Gregorb9790342010-01-22 21:44:22 +00001448CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1449 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001450 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001451
Douglas Gregorb9790342010-01-22 21:44:22 +00001452 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1453
Ted Kremeneka297de22010-01-25 22:34:44 +00001454 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001455 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1456 if (SLoc.isValid()) {
1457 SourceRange RegionOfInterest(SLoc,
1458 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1459
1460 // FIXME: Would be great to have a "hint" cursor, then walk from that
1461 // hint cursor upward until we find a cursor whose source range encloses
1462 // the region of interest, rather than starting from the translation unit.
1463 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1464 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1465 Decl::MaxPCHLevel, RegionOfInterest);
1466 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001467 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001468 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001469}
1470
Ted Kremenek73885552009-11-17 19:28:59 +00001471CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001472 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001473}
1474
1475unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001476 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001477}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001478
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001479unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001480 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1481}
1482
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001483unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001484 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1485}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001486
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001487unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001488 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1489}
1490
Douglas Gregor97b98722010-01-19 23:20:36 +00001491unsigned clang_isExpression(enum CXCursorKind K) {
1492 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1493}
1494
1495unsigned clang_isStatement(enum CXCursorKind K) {
1496 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1497}
1498
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001499unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1500 return K == CXCursor_TranslationUnit;
1501}
1502
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001503CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001504 return C.kind;
1505}
1506
Douglas Gregor97b98722010-01-19 23:20:36 +00001507static SourceLocation getLocationFromExpr(Expr *E) {
1508 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1509 return /*FIXME:*/Msg->getLeftLoc();
1510 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1511 return DRE->getLocation();
1512 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1513 return Member->getMemberLoc();
1514 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1515 return Ivar->getLocation();
1516 return E->getLocStart();
1517}
1518
Douglas Gregor98258af2010-01-18 22:46:11 +00001519CXSourceLocation clang_getCursorLocation(CXCursor C) {
1520 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001521 switch (C.kind) {
1522 case CXCursor_ObjCSuperClassRef: {
1523 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1524 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001525 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001526 }
1527
1528 case CXCursor_ObjCProtocolRef: {
1529 std::pair<ObjCProtocolDecl *, SourceLocation> P
1530 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001531 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001532 }
1533
1534 case CXCursor_ObjCClassRef: {
1535 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1536 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001537 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001538 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001539
1540 case CXCursor_TypeRef: {
1541 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001542 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001543 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001544
Douglas Gregorf46034a2010-01-18 23:41:10 +00001545 default:
1546 // FIXME: Need a way to enumerate all non-reference cases.
1547 llvm_unreachable("Missed a reference kind");
1548 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001549 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001550
1551 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001552 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001553 getLocationFromExpr(getCursorExpr(C)));
1554
Douglas Gregor5352ac02010-01-28 00:27:43 +00001555 if (!getCursorDecl(C))
1556 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001557
Douglas Gregorf46034a2010-01-18 23:41:10 +00001558 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001559 SourceLocation Loc = D->getLocation();
1560 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1561 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001562 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001563}
Douglas Gregora7bde202010-01-19 00:34:46 +00001564
1565CXSourceRange clang_getCursorExtent(CXCursor C) {
1566 if (clang_isReference(C.kind)) {
1567 switch (C.kind) {
1568 case CXCursor_ObjCSuperClassRef: {
1569 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1570 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001571 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001572 }
1573
1574 case CXCursor_ObjCProtocolRef: {
1575 std::pair<ObjCProtocolDecl *, SourceLocation> P
1576 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001577 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001578 }
1579
1580 case CXCursor_ObjCClassRef: {
1581 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1582 = getCursorObjCClassRef(C);
1583
Ted Kremeneka297de22010-01-25 22:34:44 +00001584 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001585 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001586
1587 case CXCursor_TypeRef: {
1588 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001589 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001590 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001591
Douglas Gregora7bde202010-01-19 00:34:46 +00001592 default:
1593 // FIXME: Need a way to enumerate all non-reference cases.
1594 llvm_unreachable("Missed a reference kind");
1595 }
1596 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001597
1598 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001599 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001600 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001601
1602 if (clang_isStatement(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001603 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001604 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001605
Douglas Gregor5352ac02010-01-28 00:27:43 +00001606 if (!getCursorDecl(C))
1607 return clang_getNullRange();
Douglas Gregora7bde202010-01-19 00:34:46 +00001608
1609 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001610 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001611}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001612
1613CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001614 if (clang_isInvalid(C.kind))
1615 return clang_getNullCursor();
1616
1617 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001618 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001619 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001620
Douglas Gregor97b98722010-01-19 23:20:36 +00001621 if (clang_isExpression(C.kind)) {
1622 Decl *D = getDeclFromExpr(getCursorExpr(C));
1623 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001624 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001625 return clang_getNullCursor();
1626 }
1627
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001628 if (!clang_isReference(C.kind))
1629 return clang_getNullCursor();
1630
1631 switch (C.kind) {
1632 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001633 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001634
1635 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001636 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001637
1638 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001639 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001640
1641 case CXCursor_TypeRef:
1642 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001643
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001644 default:
1645 // We would prefer to enumerate all non-reference cursor kinds here.
1646 llvm_unreachable("Unhandled reference cursor kind");
1647 break;
1648 }
1649 }
1650
1651 return clang_getNullCursor();
1652}
1653
Douglas Gregorb6998662010-01-19 19:34:47 +00001654CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001655 if (clang_isInvalid(C.kind))
1656 return clang_getNullCursor();
1657
1658 ASTUnit *CXXUnit = getCursorASTUnit(C);
1659
Douglas Gregorb6998662010-01-19 19:34:47 +00001660 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001661 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001662 C = clang_getCursorReferenced(C);
1663 WasReference = true;
1664 }
1665
1666 if (!clang_isDeclaration(C.kind))
1667 return clang_getNullCursor();
1668
1669 Decl *D = getCursorDecl(C);
1670 if (!D)
1671 return clang_getNullCursor();
1672
1673 switch (D->getKind()) {
1674 // Declaration kinds that don't really separate the notions of
1675 // declaration and definition.
1676 case Decl::Namespace:
1677 case Decl::Typedef:
1678 case Decl::TemplateTypeParm:
1679 case Decl::EnumConstant:
1680 case Decl::Field:
1681 case Decl::ObjCIvar:
1682 case Decl::ObjCAtDefsField:
1683 case Decl::ImplicitParam:
1684 case Decl::ParmVar:
1685 case Decl::NonTypeTemplateParm:
1686 case Decl::TemplateTemplateParm:
1687 case Decl::ObjCCategoryImpl:
1688 case Decl::ObjCImplementation:
1689 case Decl::LinkageSpec:
1690 case Decl::ObjCPropertyImpl:
1691 case Decl::FileScopeAsm:
1692 case Decl::StaticAssert:
1693 case Decl::Block:
1694 return C;
1695
1696 // Declaration kinds that don't make any sense here, but are
1697 // nonetheless harmless.
1698 case Decl::TranslationUnit:
1699 case Decl::Template:
1700 case Decl::ObjCContainer:
1701 break;
1702
1703 // Declaration kinds for which the definition is not resolvable.
1704 case Decl::UnresolvedUsingTypename:
1705 case Decl::UnresolvedUsingValue:
1706 break;
1707
1708 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001709 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1710 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001711
1712 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001713 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001714
1715 case Decl::Enum:
1716 case Decl::Record:
1717 case Decl::CXXRecord:
1718 case Decl::ClassTemplateSpecialization:
1719 case Decl::ClassTemplatePartialSpecialization:
1720 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001721 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001722 return clang_getNullCursor();
1723
1724 case Decl::Function:
1725 case Decl::CXXMethod:
1726 case Decl::CXXConstructor:
1727 case Decl::CXXDestructor:
1728 case Decl::CXXConversion: {
1729 const FunctionDecl *Def = 0;
1730 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001731 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001732 return clang_getNullCursor();
1733 }
1734
1735 case Decl::Var: {
1736 VarDecl *Var = cast<VarDecl>(D);
1737
1738 // Variables with initializers have definitions.
1739 const VarDecl *Def = 0;
1740 if (Var->getDefinition(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001741 return MakeCXCursor(const_cast<VarDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001742
1743 // extern and private_extern variables are not definitions.
1744 if (Var->hasExternalStorage())
1745 return clang_getNullCursor();
1746
1747 // In-line static data members do not have definitions.
1748 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1749 return clang_getNullCursor();
1750
1751 // All other variables are themselves definitions.
1752 return C;
1753 }
1754
1755 case Decl::FunctionTemplate: {
1756 const FunctionDecl *Def = 0;
1757 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001758 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001759 return clang_getNullCursor();
1760 }
1761
1762 case Decl::ClassTemplate: {
1763 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1764 ->getDefinition(D->getASTContext()))
1765 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001766 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1767 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001768 return clang_getNullCursor();
1769 }
1770
1771 case Decl::Using: {
1772 UsingDecl *Using = cast<UsingDecl>(D);
1773 CXCursor Def = clang_getNullCursor();
1774 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1775 SEnd = Using->shadow_end();
1776 S != SEnd; ++S) {
1777 if (Def != clang_getNullCursor()) {
1778 // FIXME: We have no way to return multiple results.
1779 return clang_getNullCursor();
1780 }
1781
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001782 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1783 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001784 }
1785
1786 return Def;
1787 }
1788
1789 case Decl::UsingShadow:
1790 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001791 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1792 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001793
1794 case Decl::ObjCMethod: {
1795 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1796 if (Method->isThisDeclarationADefinition())
1797 return C;
1798
1799 // Dig out the method definition in the associated
1800 // @implementation, if we have it.
1801 // FIXME: The ASTs should make finding the definition easier.
1802 if (ObjCInterfaceDecl *Class
1803 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1804 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1805 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1806 Method->isInstanceMethod()))
1807 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001808 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001809
1810 return clang_getNullCursor();
1811 }
1812
1813 case Decl::ObjCCategory:
1814 if (ObjCCategoryImplDecl *Impl
1815 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001816 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001817 return clang_getNullCursor();
1818
1819 case Decl::ObjCProtocol:
1820 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1821 return C;
1822 return clang_getNullCursor();
1823
1824 case Decl::ObjCInterface:
1825 // There are two notions of a "definition" for an Objective-C
1826 // class: the interface and its implementation. When we resolved a
1827 // reference to an Objective-C class, produce the @interface as
1828 // the definition; when we were provided with the interface,
1829 // produce the @implementation as the definition.
1830 if (WasReference) {
1831 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1832 return C;
1833 } else if (ObjCImplementationDecl *Impl
1834 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001835 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001836 return clang_getNullCursor();
1837
1838 case Decl::ObjCProperty:
1839 // FIXME: We don't really know where to find the
1840 // ObjCPropertyImplDecls that implement this property.
1841 return clang_getNullCursor();
1842
1843 case Decl::ObjCCompatibleAlias:
1844 if (ObjCInterfaceDecl *Class
1845 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1846 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001847 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001848
1849 return clang_getNullCursor();
1850
1851 case Decl::ObjCForwardProtocol: {
1852 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1853 if (Forward->protocol_size() == 1)
1854 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001855 MakeCXCursor(*Forward->protocol_begin(),
1856 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001857
1858 // FIXME: Cannot return multiple definitions.
1859 return clang_getNullCursor();
1860 }
1861
1862 case Decl::ObjCClass: {
1863 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1864 if (Class->size() == 1) {
1865 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1866 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001867 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001868 return clang_getNullCursor();
1869 }
1870
1871 // FIXME: Cannot return multiple definitions.
1872 return clang_getNullCursor();
1873 }
1874
1875 case Decl::Friend:
1876 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001877 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001878 return clang_getNullCursor();
1879
1880 case Decl::FriendTemplate:
1881 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001882 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001883 return clang_getNullCursor();
1884 }
1885
1886 return clang_getNullCursor();
1887}
1888
1889unsigned clang_isCursorDefinition(CXCursor C) {
1890 if (!clang_isDeclaration(C.kind))
1891 return 0;
1892
1893 return clang_getCursorDefinition(C) == C;
1894}
1895
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001896void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001897 const char **startBuf,
1898 const char **endBuf,
1899 unsigned *startLine,
1900 unsigned *startColumn,
1901 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001902 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001903 assert(getCursorDecl(C) && "CXCursor has null decl");
1904 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001905 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1906 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001907
Steve Naroff4ade6d62009-09-23 17:52:52 +00001908 SourceManager &SM = FD->getASTContext().getSourceManager();
1909 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1910 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1911 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1912 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1913 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1914 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1915}
Ted Kremenekfb480492010-01-13 21:46:36 +00001916
1917} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001918
Ted Kremenekfb480492010-01-13 21:46:36 +00001919//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001920// Token-based Operations.
1921//===----------------------------------------------------------------------===//
1922
1923/* CXToken layout:
1924 * int_data[0]: a CXTokenKind
1925 * int_data[1]: starting token location
1926 * int_data[2]: token length
1927 * int_data[3]: reserved
1928 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
1929 * otherwise unused.
1930 */
1931extern "C" {
1932
1933CXTokenKind clang_getTokenKind(CXToken CXTok) {
1934 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1935}
1936
1937CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1938 switch (clang_getTokenKind(CXTok)) {
1939 case CXToken_Identifier:
1940 case CXToken_Keyword:
1941 // We know we have an IdentifierInfo*, so use that.
1942 return CIndexer::createCXString(
1943 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
1944
1945 case CXToken_Literal: {
1946 // We have stashed the starting pointer in the ptr_data field. Use it.
1947 const char *Text = static_cast<const char *>(CXTok.ptr_data);
1948 return CIndexer::createCXString(llvm::StringRef(Text, CXTok.int_data[2]),
1949 true);
1950 }
1951
1952 case CXToken_Punctuation:
1953 case CXToken_Comment:
1954 break;
1955 }
1956
1957 // We have to find the starting buffer pointer the hard way, by
1958 // deconstructing the source location.
1959 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1960 if (!CXXUnit)
1961 return CIndexer::createCXString("");
1962
1963 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1964 std::pair<FileID, unsigned> LocInfo
1965 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1966 std::pair<const char *,const char *> Buffer
1967 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1968
1969 return CIndexer::createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1970 CXTok.int_data[2]),
1971 true);
1972}
1973
1974CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1975 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1976 if (!CXXUnit)
1977 return clang_getNullLocation();
1978
1979 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1980 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1981}
1982
1983CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1984 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001985 if (!CXXUnit)
1986 return clang_getNullRange();
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001987
1988 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
1989 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1990}
1991
1992void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1993 CXToken **Tokens, unsigned *NumTokens) {
1994 if (Tokens)
1995 *Tokens = 0;
1996 if (NumTokens)
1997 *NumTokens = 0;
1998
1999 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2000 if (!CXXUnit || !Tokens || !NumTokens)
2001 return;
2002
2003 SourceRange R = cxloc::translateSourceRange(Range);
2004 if (R.isInvalid())
2005 return;
2006
2007 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2008 std::pair<FileID, unsigned> BeginLocInfo
2009 = SourceMgr.getDecomposedLoc(R.getBegin());
2010 std::pair<FileID, unsigned> EndLocInfo
2011 = SourceMgr.getDecomposedLoc(R.getEnd());
2012
2013 // Cannot tokenize across files.
2014 if (BeginLocInfo.first != EndLocInfo.first)
2015 return;
2016
2017 // Create a lexer
2018 std::pair<const char *,const char *> Buffer
2019 = SourceMgr.getBufferData(BeginLocInfo.first);
2020 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2021 CXXUnit->getASTContext().getLangOptions(),
2022 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
2023 Lex.SetCommentRetentionState(true);
2024
2025 // Lex tokens until we hit the end of the range.
2026 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
2027 llvm::SmallVector<CXToken, 32> CXTokens;
2028 Token Tok;
2029 do {
2030 // Lex the next token
2031 Lex.LexFromRawLexer(Tok);
2032 if (Tok.is(tok::eof))
2033 break;
2034
2035 // Initialize the CXToken.
2036 CXToken CXTok;
2037
2038 // - Common fields
2039 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2040 CXTok.int_data[2] = Tok.getLength();
2041 CXTok.int_data[3] = 0;
2042
2043 // - Kind-specific fields
2044 if (Tok.isLiteral()) {
2045 CXTok.int_data[0] = CXToken_Literal;
2046 CXTok.ptr_data = (void *)Tok.getLiteralData();
2047 } else if (Tok.is(tok::identifier)) {
2048 // Lookup the identifier to determine whether we have a
2049 std::pair<FileID, unsigned> LocInfo
2050 = SourceMgr.getDecomposedLoc(Tok.getLocation());
2051 const char *StartPos
2052 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
2053 LocInfo.second;
2054 IdentifierInfo *II
2055 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2056 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2057 CXToken_Identifier
2058 : CXToken_Keyword;
2059 CXTok.ptr_data = II;
2060 } else if (Tok.is(tok::comment)) {
2061 CXTok.int_data[0] = CXToken_Comment;
2062 CXTok.ptr_data = 0;
2063 } else {
2064 CXTok.int_data[0] = CXToken_Punctuation;
2065 CXTok.ptr_data = 0;
2066 }
2067 CXTokens.push_back(CXTok);
2068 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2069
2070 if (CXTokens.empty())
2071 return;
2072
2073 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2074 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2075 *NumTokens = CXTokens.size();
2076}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002077
2078typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2079
2080enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2081 CXCursor parent,
2082 CXClientData client_data) {
2083 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2084
2085 // We only annotate the locations of declarations, simple
2086 // references, and expressions which directly reference something.
2087 CXCursorKind Kind = clang_getCursorKind(cursor);
2088 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2089 // Okay: We can annotate the location of this declaration with the
2090 // declaration or reference
2091 } else if (clang_isExpression(cursor.kind)) {
2092 if (Kind != CXCursor_DeclRefExpr &&
2093 Kind != CXCursor_MemberRefExpr &&
2094 Kind != CXCursor_ObjCMessageExpr)
2095 return CXChildVisit_Recurse;
2096
2097 CXCursor Referenced = clang_getCursorReferenced(cursor);
2098 if (Referenced == cursor || Referenced == clang_getNullCursor())
2099 return CXChildVisit_Recurse;
2100
2101 // Okay: we can annotate the location of this expression
2102 } else {
2103 // Nothing to annotate
2104 return CXChildVisit_Recurse;
2105 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002106
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002107 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2108 (*Data)[Loc.int_data] = cursor;
2109 return CXChildVisit_Recurse;
2110}
2111
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002112void clang_annotateTokens(CXTranslationUnit TU,
2113 CXToken *Tokens, unsigned NumTokens,
2114 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002115 if (NumTokens == 0)
2116 return;
2117
2118 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002119 for (unsigned I = 0; I != NumTokens; ++I)
2120 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002121
2122 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2123 if (!CXXUnit || !Tokens)
2124 return;
2125
2126 // Annotate all of the source locations in the region of interest that map
2127 SourceRange RegionOfInterest;
2128 RegionOfInterest.setBegin(
2129 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2130 SourceLocation End
2131 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2132 Tokens[NumTokens - 1]));
2133 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End,
2134 1));
2135 // FIXME: Would be great to have a "hint" cursor, then walk from that
2136 // hint cursor upward until we find a cursor whose source range encloses
2137 // the region of interest, rather than starting from the translation unit.
2138 AnnotateTokensData Annotated;
2139 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2140 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2141 Decl::MaxPCHLevel, RegionOfInterest);
2142 AnnotateVis.VisitChildren(Parent);
2143
2144 for (unsigned I = 0; I != NumTokens; ++I) {
2145 // Determine whether we saw a cursor at this token's location.
2146 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2147 if (Pos == Annotated.end())
2148 continue;
2149
2150 Cursors[I] = Pos->second;
2151 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002152}
2153
2154void clang_disposeTokens(CXTranslationUnit TU,
2155 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002156 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002157}
2158
2159} // end: extern "C"
2160
2161//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002162// CXString Operations.
2163//===----------------------------------------------------------------------===//
2164
2165extern "C" {
2166const char *clang_getCString(CXString string) {
2167 return string.Spelling;
2168}
2169
2170void clang_disposeString(CXString string) {
2171 if (string.MustFreeString && string.Spelling)
2172 free((void*)string.Spelling);
2173}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002174
Ted Kremenekfb480492010-01-13 21:46:36 +00002175} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002176
2177//===----------------------------------------------------------------------===//
2178// Misc. utility functions.
2179//===----------------------------------------------------------------------===//
2180
2181extern "C" {
2182
2183const char *clang_getClangVersion() {
Ted Kremeneka18f1b82010-01-23 02:11:34 +00002184 return getClangFullVersion();
Ted Kremenek04bb7162010-01-22 22:44:15 +00002185}
2186
2187} // end: extern "C"
2188