blob: 57b463cba0c88fe8e84d3c9ed9498edf166db04f [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.
289 R.setEnd(TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1));
290 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
291}
292
293RangeComparisonResult CursorVisitor::CompareRegionOfInterest(CXSourceRange CXR) {
Ted Kremeneka297de22010-01-25 22:34:44 +0000294 return CompareRegionOfInterest(cxloc::translateSourceRange(CXR));
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000295}
296
Douglas Gregorb1373d02010-01-20 20:59:29 +0000297/// \brief Visit the given cursor and, if requested by the visitor,
298/// its children.
299///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000300/// \param Cursor the cursor to visit.
301///
302/// \param CheckRegionOfInterest if true, then the caller already checked that
303/// this cursor is within the region of interest.
304///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000305/// \returns true if the visitation should be aborted, false if it
306/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000307bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000308 if (clang_isInvalid(Cursor.kind))
309 return false;
310
311 if (clang_isDeclaration(Cursor.kind)) {
312 Decl *D = getCursorDecl(Cursor);
313 assert(D && "Invalid declaration cursor");
314 if (D->getPCHLevel() > MaxPCHLevel)
315 return false;
316
317 if (D->isImplicit())
318 return false;
319 }
320
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000321 // If we have a range of interest, and this cursor doesn't intersect with it,
322 // we're done.
323 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
324 CXSourceRange Range = clang_getCursorExtent(Cursor);
Ted Kremeneka297de22010-01-25 22:34:44 +0000325 if (cxloc::translateSourceRange(Range).isInvalid() ||
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000326 CompareRegionOfInterest(Range))
327 return false;
328 }
329
Douglas Gregorb1373d02010-01-20 20:59:29 +0000330 switch (Visitor(Cursor, Parent, ClientData)) {
331 case CXChildVisit_Break:
332 return true;
333
334 case CXChildVisit_Continue:
335 return false;
336
337 case CXChildVisit_Recurse:
338 return VisitChildren(Cursor);
339 }
340
Douglas Gregorfd643772010-01-25 16:45:46 +0000341 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000342}
343
344/// \brief Visit the children of the given cursor.
345///
346/// \returns true if the visitation should be aborted, false if it
347/// should continue.
348bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000349 if (clang_isReference(Cursor.kind)) {
350 // By definition, references have no children.
351 return false;
352 }
353
Douglas Gregorb1373d02010-01-20 20:59:29 +0000354 // Set the Parent field to Cursor, then back to its old value once we're
355 // done.
356 class SetParentRAII {
357 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000358 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000359 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000360
Douglas Gregorb1373d02010-01-20 20:59:29 +0000361 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000362 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
363 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000364 {
365 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000366 if (clang_isDeclaration(Parent.kind))
367 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000368 }
369
370 ~SetParentRAII() {
371 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000372 if (clang_isDeclaration(Parent.kind))
373 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000375 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376
377 if (clang_isDeclaration(Cursor.kind)) {
378 Decl *D = getCursorDecl(Cursor);
379 assert(D && "Invalid declaration cursor");
380 return Visit(D);
381 }
382
Douglas Gregora59e3902010-01-21 23:27:09 +0000383 if (clang_isStatement(Cursor.kind))
384 return Visit(getCursorStmt(Cursor));
385 if (clang_isExpression(Cursor.kind))
386 return Visit(getCursorExpr(Cursor));
387
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000389 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000390 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
391 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000392 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
393 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
394 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000395 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000396 return true;
397 }
398 } else {
399 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000401 }
402
403 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000404 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000405
Douglas Gregorb1373d02010-01-20 20:59:29 +0000406 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407 return false;
408}
409
Douglas Gregorb1373d02010-01-20 20:59:29 +0000410bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000411 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000413 if (RegionOfInterest.isValid()) {
414 SourceRange R = (*I)->getSourceRange();
415 if (R.isInvalid())
416 continue;
417
418 switch (CompareRegionOfInterest(R)) {
419 case RangeBefore:
420 // This declaration comes before the region of interest; skip it.
421 continue;
422
423 case RangeAfter:
424 // This declaration comes after the region of interest; we're done.
425 return false;
426
427 case RangeOverlap:
428 // This declaration overlaps the region of interest; visit it.
429 break;
430 }
431 }
432
433 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434 return true;
435 }
436
437 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000438}
439
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000440bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
441 llvm_unreachable("Translation units are visited directly by Visit()");
442 return false;
443}
444
445bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
446 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
447 return Visit(TSInfo->getTypeLoc());
448
449 return false;
450}
451
452bool CursorVisitor::VisitTagDecl(TagDecl *D) {
453 return VisitDeclContext(D);
454}
455
456bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
457 if (Expr *Init = D->getInitExpr())
458 return Visit(MakeCXCursor(Init, StmtParent, TU));
459 return false;
460}
461
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000462bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
463 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
464 if (Visit(TSInfo->getTypeLoc()))
465 return true;
466
467 return false;
468}
469
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000471 if (VisitDeclaratorDecl(ND))
472 return true;
473
Douglas Gregora59e3902010-01-21 23:27:09 +0000474 if (ND->isThisDeclarationADefinition() &&
475 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
476 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477
478 return false;
479}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000480
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000481bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
482 if (VisitDeclaratorDecl(D))
483 return true;
484
485 if (Expr *BitWidth = D->getBitWidth())
486 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
487
488 return false;
489}
490
491bool CursorVisitor::VisitVarDecl(VarDecl *D) {
492 if (VisitDeclaratorDecl(D))
493 return true;
494
495 if (Expr *Init = D->getInit())
496 return Visit(MakeCXCursor(Init, StmtParent, TU));
497
498 return false;
499}
500
501bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
502 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
503 // At the moment, we don't have information about locations in the return
504 // type.
505 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
506 PEnd = ND->param_end();
507 P != PEnd; ++P) {
508 if (Visit(MakeCXCursor(*P, TU)))
509 return true;
510 }
511
512 if (ND->isThisDeclarationADefinition() &&
513 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
514 return true;
515
516 return false;
517}
518
Douglas Gregora59e3902010-01-21 23:27:09 +0000519bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
520 return VisitDeclContext(D);
521}
522
Douglas Gregorb1373d02010-01-20 20:59:29 +0000523bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000524 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
525 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 return true;
527
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000528 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
529 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
530 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000531 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000532 return true;
533
Douglas Gregora59e3902010-01-21 23:27:09 +0000534 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000535}
536
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000537bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
538 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
539 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
540 E = PID->protocol_end(); I != E; ++I, ++PL)
541 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
542 return true;
543
544 return VisitObjCContainerDecl(PID);
545}
546
Douglas Gregorb1373d02010-01-20 20:59:29 +0000547bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000548 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000549 if (D->getSuperClass() &&
550 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000551 D->getSuperClassLoc(),
552 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000553 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000554
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000555 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
556 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
557 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000558 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 return true;
560
Douglas Gregora59e3902010-01-21 23:27:09 +0000561 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000562}
563
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000564bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
565 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000566}
567
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000568bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
569 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
570 D->getLocation(), TU)))
571 return true;
572
573 return VisitObjCImplDecl(D);
574}
575
576bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
577#if 0
578 // Issue callbacks for super class.
579 // FIXME: No source location information!
580 if (D->getSuperClass() &&
581 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
582 D->getSuperClassLoc(),
583 TU)))
584 return true;
585#endif
586
587 return VisitObjCImplDecl(D);
588}
589
590bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
591 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
592 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
593 E = D->protocol_end();
594 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000595 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000596 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000599}
600
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000601bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
602 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
603 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
604 return true;
605
606 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000607}
608
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000609bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
610 ASTContext &Context = TU->getASTContext();
611
612 // Some builtin types (such as Objective-C's "id", "sel", and
613 // "Class") have associated declarations. Create cursors for those.
614 QualType VisitType;
615 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
616 case BuiltinType::Void:
617 case BuiltinType::Bool:
618 case BuiltinType::Char_U:
619 case BuiltinType::UChar:
620 case BuiltinType::Char16:
621 case BuiltinType::Char32:
622 case BuiltinType::UShort:
623 case BuiltinType::UInt:
624 case BuiltinType::ULong:
625 case BuiltinType::ULongLong:
626 case BuiltinType::UInt128:
627 case BuiltinType::Char_S:
628 case BuiltinType::SChar:
629 case BuiltinType::WChar:
630 case BuiltinType::Short:
631 case BuiltinType::Int:
632 case BuiltinType::Long:
633 case BuiltinType::LongLong:
634 case BuiltinType::Int128:
635 case BuiltinType::Float:
636 case BuiltinType::Double:
637 case BuiltinType::LongDouble:
638 case BuiltinType::NullPtr:
639 case BuiltinType::Overload:
640 case BuiltinType::Dependent:
641 break;
642
643 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
644 break;
645
646 case BuiltinType::ObjCId:
647 VisitType = Context.getObjCIdType();
648 break;
649
650 case BuiltinType::ObjCClass:
651 VisitType = Context.getObjCClassType();
652 break;
653
654 case BuiltinType::ObjCSel:
655 VisitType = Context.getObjCSelType();
656 break;
657 }
658
659 if (!VisitType.isNull()) {
660 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
661 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
662 TU));
663 }
664
665 return false;
666}
667
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000668bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
669 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
670}
671
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000672bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
673 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
674}
675
676bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
677 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
678}
679
680bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
681 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
682 return true;
683
684 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
685 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
686 TU)))
687 return true;
688 }
689
690 return false;
691}
692
693bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
694 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
695 return true;
696
697 if (TL.hasProtocolsAsWritten()) {
698 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
699 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
700 TL.getProtocolLoc(I),
701 TU)))
702 return true;
703 }
704 }
705
706 return false;
707}
708
709bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
710 return Visit(TL.getPointeeLoc());
711}
712
713bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
714 return Visit(TL.getPointeeLoc());
715}
716
717bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
718 return Visit(TL.getPointeeLoc());
719}
720
721bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
722 return Visit(TL.getPointeeLoc());
723}
724
725bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
726 return Visit(TL.getPointeeLoc());
727}
728
729bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
730 if (Visit(TL.getResultLoc()))
731 return true;
732
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000733 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
734 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
735 return true;
736
737 return false;
738}
739
740bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
741 if (Visit(TL.getElementLoc()))
742 return true;
743
744 if (Expr *Size = TL.getSizeExpr())
745 return Visit(MakeCXCursor(Size, StmtParent, TU));
746
747 return false;
748}
749
Douglas Gregor2332c112010-01-21 20:48:56 +0000750bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
751 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
752}
753
754bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
755 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
756 return Visit(TSInfo->getTypeLoc());
757
758 return false;
759}
760
Douglas Gregora59e3902010-01-21 23:27:09 +0000761bool CursorVisitor::VisitStmt(Stmt *S) {
762 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
763 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000764 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000765 return true;
766 }
767
768 return false;
769}
770
771bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
772 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
773 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000774 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000775 return true;
776 }
777
778 return false;
779}
780
Douglas Gregorf5bab412010-01-22 01:00:11 +0000781bool CursorVisitor::VisitIfStmt(IfStmt *S) {
782 if (VarDecl *Var = S->getConditionVariable()) {
783 if (Visit(MakeCXCursor(Var, TU)))
784 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000785 }
Douglas Gregorf5bab412010-01-22 01:00:11 +0000786
Douglas Gregor263b47b2010-01-25 16:12:32 +0000787 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
788 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000789 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
790 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000791 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
792 return true;
793
794 return false;
795}
796
797bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
798 if (VarDecl *Var = S->getConditionVariable()) {
799 if (Visit(MakeCXCursor(Var, TU)))
800 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000801 }
802
803 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
804 return true;
805 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
806 return true;
807
808 return false;
809}
810
811bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
812 if (VarDecl *Var = S->getConditionVariable()) {
813 if (Visit(MakeCXCursor(Var, TU)))
814 return true;
815 }
816
817 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
818 return true;
819 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000820 return true;
821
Douglas Gregor263b47b2010-01-25 16:12:32 +0000822 return false;
823}
824
825bool CursorVisitor::VisitForStmt(ForStmt *S) {
826 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
827 return true;
828 if (VarDecl *Var = S->getConditionVariable()) {
829 if (Visit(MakeCXCursor(Var, TU)))
830 return true;
831 }
832
833 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
834 return true;
835 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
836 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000837 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
838 return true;
839
840 return false;
841}
842
Douglas Gregor336fd812010-01-23 00:40:08 +0000843bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
844 if (E->isArgumentType()) {
845 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
846 return Visit(TSInfo->getTypeLoc());
847
848 return false;
849 }
850
851 return VisitExpr(E);
852}
853
854bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
855 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
856 if (Visit(TSInfo->getTypeLoc()))
857 return true;
858
859 return VisitCastExpr(E);
860}
861
862bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
863 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
864 if (Visit(TSInfo->getTypeLoc()))
865 return true;
866
867 return VisitExpr(E);
868}
869
Daniel Dunbar140fce22010-01-12 02:34:07 +0000870CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000871 CXString Str;
872 if (DupString) {
873 Str.Spelling = strdup(String);
874 Str.MustFreeString = 1;
875 } else {
876 Str.Spelling = String;
877 Str.MustFreeString = 0;
878 }
879 return Str;
880}
881
Douglas Gregorfc8ea232010-01-26 17:06:03 +0000882CXString CIndexer::createCXString(llvm::StringRef String, bool DupString) {
883 CXString Result;
884 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
885 char *Spelling = (char *)malloc(String.size() + 1);
886 memmove(Spelling, String.data(), String.size());
887 Spelling[String.size()] = 0;
888 Result.Spelling = Spelling;
889 Result.MustFreeString = 1;
890 } else {
891 Result.Spelling = String.data();
892 Result.MustFreeString = 0;
893 }
894 return Result;
895}
896
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000897extern "C" {
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000898CXIndex clang_createIndex(int excludeDeclarationsFromPCH) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000899 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000900 if (excludeDeclarationsFromPCH)
901 CIdxr->setOnlyLocalDecls();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000902 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000903}
904
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000905void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000906 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000907 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000908}
909
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000910void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
911 assert(CIdx && "Passed null CXIndex");
912 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
913 CXXIdx->setUseExternalASTGeneration(value);
914}
915
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000916CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000917 const char *ast_filename,
918 CXDiagnosticCallback diag_callback,
919 CXClientData diag_client_data) {
Steve Naroff50398192009-08-28 15:28:48 +0000920 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000921 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000922
Douglas Gregor5352ac02010-01-28 00:27:43 +0000923 // Configure the diagnostics.
924 DiagnosticOptions DiagOpts;
925 llvm::OwningPtr<Diagnostic> Diags;
926 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
927 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
928 Diags->setClient(&DiagClient);
929
930 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000931 CXXIdx->getOnlyLocalDecls(),
932 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000933}
934
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000935CXTranslationUnit
936clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
937 const char *source_filename,
938 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000939 const char **command_line_args,
940 unsigned num_unsaved_files,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000941 struct CXUnsavedFile *unsaved_files,
942 CXDiagnosticCallback diag_callback,
943 CXClientData diag_client_data) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000944 assert(CIdx && "Passed null CXIndex");
945 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
946
Douglas Gregor5352ac02010-01-28 00:27:43 +0000947 // Configure the diagnostics.
948 DiagnosticOptions DiagOpts;
949 llvm::OwningPtr<Diagnostic> Diags;
950 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
951 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
952 Diags->setClient(&DiagClient);
953
Douglas Gregor4db64a42010-01-23 00:14:00 +0000954 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
955 for (unsigned I = 0; I != num_unsaved_files; ++I) {
956 const llvm::MemoryBuffer *Buffer
957 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
958 unsaved_files[I].Contents + unsaved_files[I].Length,
959 unsaved_files[I].Filename);
960 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
961 Buffer));
962 }
963
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000964 if (!CXXIdx->getUseExternalASTGeneration()) {
965 llvm::SmallVector<const char *, 16> Args;
966
967 // The 'source_filename' argument is optional. If the caller does not
968 // specify it then it is assumed that the source file is specified
969 // in the actual argument list.
970 if (source_filename)
971 Args.push_back(source_filename);
972 Args.insert(Args.end(), command_line_args,
973 command_line_args + num_command_line_args);
974
Douglas Gregor5352ac02010-01-28 00:27:43 +0000975 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000976
Ted Kremenek29b72842010-01-07 22:49:05 +0000977#ifdef USE_CRASHTRACER
978 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000979#endif
980
Daniel Dunbar94220972009-12-05 02:17:18 +0000981 llvm::OwningPtr<ASTUnit> Unit(
982 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor5352ac02010-01-28 00:27:43 +0000983 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +0000984 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000985 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +0000986 /* UseBumpAllocator = */ true,
987 RemappedFiles.data(),
988 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +0000989
Daniel Dunbar94220972009-12-05 02:17:18 +0000990 // FIXME: Until we have broader testing, just drop the entire AST if we
991 // encountered an error.
Douglas Gregor5352ac02010-01-28 00:27:43 +0000992 if (NumErrors != Diags->getNumErrors())
Daniel Dunbar94220972009-12-05 02:17:18 +0000993 return 0;
994
995 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000996 }
997
Ted Kremenek139ba862009-10-22 00:03:57 +0000998 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000999 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001000
Ted Kremenek139ba862009-10-22 00:03:57 +00001001 // First add the complete path to the 'clang' executable.
1002 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001003 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001004
Ted Kremenek139ba862009-10-22 00:03:57 +00001005 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001006 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001007
Ted Kremenek139ba862009-10-22 00:03:57 +00001008 // The 'source_filename' argument is optional. If the caller does not
1009 // specify it then it is assumed that the source file is specified
1010 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001011 if (source_filename)
1012 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001013
Steve Naroff37b5ac22009-10-15 20:50:09 +00001014 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001015 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +00001016 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +00001017 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001018
Douglas Gregor4db64a42010-01-23 00:14:00 +00001019 // Remap any unsaved files to temporary files.
1020 std::vector<llvm::sys::Path> TemporaryFiles;
1021 std::vector<std::string> RemapArgs;
1022 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1023 return 0;
1024
1025 // The pointers into the elements of RemapArgs are stable because we
1026 // won't be adding anything to RemapArgs after this point.
1027 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1028 argv.push_back(RemapArgs[i].c_str());
1029
Ted Kremenek139ba862009-10-22 00:03:57 +00001030 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1031 for (int i = 0; i < num_command_line_args; ++i)
1032 if (const char *arg = command_line_args[i]) {
1033 if (strcmp(arg, "-o") == 0) {
1034 ++i; // Also skip the matching argument.
1035 continue;
1036 }
1037 if (strcmp(arg, "-emit-ast") == 0 ||
1038 strcmp(arg, "-c") == 0 ||
1039 strcmp(arg, "-fsyntax-only") == 0) {
1040 continue;
1041 }
1042
1043 // Keep the argument.
1044 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001045 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001046
Ted Kremenek139ba862009-10-22 00:03:57 +00001047 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001048 argv.push_back(NULL);
1049
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001050 // Invoke 'clang'.
1051 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1052 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001053 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +00001054 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001055 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001056 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001057 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001058
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001059 if (!ErrMsg.empty()) {
1060 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001061 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001062 I != E; ++I) {
1063 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001064 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001065 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001066 }
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001067
1068 Diags->Report(diag::err_fe_clang) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001069 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001070
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001071 // FIXME: Parse the (redirected) standard error to emit diagnostics.
1072
Douglas Gregor5352ac02010-01-28 00:27:43 +00001073 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001074 CXXIdx->getOnlyLocalDecls(),
1075 /* UseBumpAllocator = */ true,
1076 RemappedFiles.data(),
1077 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001078 if (ATU)
1079 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001080
1081 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1082 TemporaryFiles[i].eraseFromDisk();
1083
Steve Naroffe19944c2009-10-15 22:23:48 +00001084 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001085}
1086
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001087void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001088 assert(CTUnit && "Passed null CXTranslationUnit");
1089 delete static_cast<ASTUnit *>(CTUnit);
1090}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001091
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001092CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001093 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +00001094 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001095 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1096 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001097}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001098
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001099CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001100 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001101 return Result;
1102}
1103
Ted Kremenekfb480492010-01-13 21:46:36 +00001104} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001105
Ted Kremenekfb480492010-01-13 21:46:36 +00001106//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001107// CXSourceLocation and CXSourceRange Operations.
1108//===----------------------------------------------------------------------===//
1109
Douglas Gregorb9790342010-01-22 21:44:22 +00001110extern "C" {
1111CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001112 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001113 return Result;
1114}
1115
1116unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
1117 return loc1.ptr_data == loc2.ptr_data && loc1.int_data == loc2.int_data;
1118}
1119
1120CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1121 CXFile file,
1122 unsigned line,
1123 unsigned column) {
1124 if (!tu)
1125 return clang_getNullLocation();
1126
1127 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1128 SourceLocation SLoc
1129 = CXXUnit->getSourceManager().getLocation(
1130 static_cast<const FileEntry *>(file),
1131 line, column);
1132
Ted Kremeneka297de22010-01-25 22:34:44 +00001133 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc, false);
Douglas Gregorb9790342010-01-22 21:44:22 +00001134}
1135
Douglas Gregor5352ac02010-01-28 00:27:43 +00001136CXSourceRange clang_getNullRange() {
1137 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1138 return Result;
1139}
Douglas Gregorb9790342010-01-22 21:44:22 +00001140
Douglas Gregor5352ac02010-01-28 00:27:43 +00001141CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1142 if (begin.ptr_data[0] != end.ptr_data[0] ||
1143 begin.ptr_data[1] != end.ptr_data[1])
1144 return clang_getNullRange();
1145
1146 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1147 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001148 return Result;
1149}
1150
Douglas Gregor46766dc2010-01-26 19:19:08 +00001151void clang_getInstantiationLocation(CXSourceLocation location,
1152 CXFile *file,
1153 unsigned *line,
1154 unsigned *column,
1155 unsigned *offset) {
Ted Kremeneka297de22010-01-25 22:34:44 +00001156 cxloc::CXSourceLocationPtr Ptr
Douglas Gregor5352ac02010-01-28 00:27:43 +00001157 = cxloc::CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001158 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1159
Douglas Gregor46766dc2010-01-26 19:19:08 +00001160 if (!Ptr.getPointer() || Loc.isInvalid()) {
1161 if (file)
1162 *file = 0;
1163 if (line)
1164 *line = 0;
1165 if (column)
1166 *column = 0;
1167 if (offset)
1168 *offset = 0;
1169 return;
1170 }
1171
Douglas Gregor1db19de2010-01-19 21:36:55 +00001172 // FIXME: This is largely copy-paste from
1173 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
1174 // what we want the two routines should be refactored.
Douglas Gregor5352ac02010-01-28 00:27:43 +00001175 const SourceManager &SM = *Ptr.getPointer();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001176 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1177
1178 if (Ptr.getInt()) {
1179 // We want the last character in this location, so we will adjust
1180 // the instantiation location accordingly.
1181
1182 // If the location is from a macro instantiation, get the end of
1183 // the instantiation range.
1184 if (Loc.isMacroID())
1185 InstLoc = SM.getInstantiationRange(Loc).second;
1186
1187 // Measure the length token we're pointing at, so we can adjust
1188 // the physical location in the file to point at the last
1189 // character.
1190 // FIXME: This won't cope with trigraphs or escaped newlines
1191 // well. For that, we actually need a preprocessor, which isn't
1192 // currently available here. Eventually, we'll switch the pointer
1193 // data of CXSourceLocation/CXSourceRange to a translation unit
1194 // (CXXUnit), so that the preprocessor will be available here. At
1195 // that point, we can use Preprocessor::getLocForEndOfToken().
1196 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
Douglas Gregor5352ac02010-01-28 00:27:43 +00001197 *static_cast<LangOptions *>(location.ptr_data[1]));
Douglas Gregor1db19de2010-01-19 21:36:55 +00001198 if (Length > 0)
1199 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
1200 }
1201
1202 if (file)
1203 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1204 if (line)
1205 *line = SM.getInstantiationLineNumber(InstLoc);
1206 if (column)
1207 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001208 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001209 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001210}
1211
Douglas Gregor1db19de2010-01-19 21:36:55 +00001212CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001213 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1214 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001215 return Result;
1216}
1217
1218CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001219 cxloc::CXSourceLocationPtr Ptr;
1220 Ptr.setPointer(static_cast<SourceManager *>(range.ptr_data[0]));
Douglas Gregor1db19de2010-01-19 21:36:55 +00001221 Ptr.setInt(true);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001222 CXSourceLocation Result = { { Ptr.getOpaqueValue(), range.ptr_data[1] },
1223 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001224 return Result;
1225}
1226
Douglas Gregorb9790342010-01-22 21:44:22 +00001227} // end: extern "C"
1228
Douglas Gregor1db19de2010-01-19 21:36:55 +00001229//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001230// CXFile Operations.
1231//===----------------------------------------------------------------------===//
1232
1233extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001234const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001235 if (!SFile)
1236 return 0;
1237
Steve Naroff88145032009-10-27 14:35:18 +00001238 assert(SFile && "Passed null CXFile");
1239 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1240 return FEnt->getName();
1241}
1242
1243time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001244 if (!SFile)
1245 return 0;
1246
Steve Naroff88145032009-10-27 14:35:18 +00001247 assert(SFile && "Passed null CXFile");
1248 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1249 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001250}
Douglas Gregorb9790342010-01-22 21:44:22 +00001251
1252CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1253 if (!tu)
1254 return 0;
1255
1256 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1257
1258 FileManager &FMgr = CXXUnit->getFileManager();
1259 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1260 return const_cast<FileEntry *>(File);
1261}
1262
Ted Kremenekfb480492010-01-13 21:46:36 +00001263} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001264
Ted Kremenekfb480492010-01-13 21:46:36 +00001265//===----------------------------------------------------------------------===//
1266// CXCursor Operations.
1267//===----------------------------------------------------------------------===//
1268
Ted Kremenekfb480492010-01-13 21:46:36 +00001269static Decl *getDeclFromExpr(Stmt *E) {
1270 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1271 return RefExpr->getDecl();
1272 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1273 return ME->getMemberDecl();
1274 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1275 return RE->getDecl();
1276
1277 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1278 return getDeclFromExpr(CE->getCallee());
1279 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1280 return getDeclFromExpr(CE->getSubExpr());
1281 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1282 return OME->getMethodDecl();
1283
1284 return 0;
1285}
1286
1287extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001288
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001289unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001290 CXCursorVisitor visitor,
1291 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001292 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001293
1294 unsigned PCHLevel = Decl::MaxPCHLevel;
1295
1296 // Set the PCHLevel to filter out unwanted decls if requested.
1297 if (CXXUnit->getOnlyLocalDecls()) {
1298 PCHLevel = 0;
1299
1300 // If the main input was an AST, bump the level.
1301 if (CXXUnit->isMainFileAST())
1302 ++PCHLevel;
1303 }
1304
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001305 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001306 return CursorVis.VisitChildren(parent);
1307}
1308
Douglas Gregor78205d42010-01-20 21:45:58 +00001309static CXString getDeclSpelling(Decl *D) {
1310 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1311 if (!ND)
1312 return CIndexer::createCXString("");
1313
1314 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1315 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1316 true);
1317
1318 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1319 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1320 // and returns different names. NamedDecl returns the class name and
1321 // ObjCCategoryImplDecl returns the category name.
1322 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1323
1324 if (ND->getIdentifier())
1325 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1326
1327 return CIndexer::createCXString("");
1328}
1329
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001330CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +00001331 assert(getCursorDecl(C) && "CXCursor has null decl");
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001332 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001333 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001334
Steve Narofff334b4e2009-09-02 18:26:48 +00001335 if (clang_isReference(C.kind)) {
1336 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001337 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001338 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1339 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001340 }
1341 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001342 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1343 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001344 }
1345 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001346 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001347 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001348 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001349 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001350 case CXCursor_TypeRef: {
1351 TypeDecl *Type = getCursorTypeRef(C).first;
1352 assert(Type && "Missing type decl");
1353
1354 return CIndexer::createCXString(
1355 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1356 true);
1357 }
1358
Daniel Dunbaracca7252009-11-30 20:42:49 +00001359 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001360 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001361 }
1362 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001363
1364 if (clang_isExpression(C.kind)) {
1365 Decl *D = getDeclFromExpr(getCursorExpr(C));
1366 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001367 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001368 return CIndexer::createCXString("");
1369 }
1370
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001371 if (clang_isDeclaration(C.kind))
1372 return getDeclSpelling(getCursorDecl(C));
1373
1374 return CIndexer::createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001375}
1376
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001377const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001378 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001379 case CXCursor_FunctionDecl: return "FunctionDecl";
1380 case CXCursor_TypedefDecl: return "TypedefDecl";
1381 case CXCursor_EnumDecl: return "EnumDecl";
1382 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1383 case CXCursor_StructDecl: return "StructDecl";
1384 case CXCursor_UnionDecl: return "UnionDecl";
1385 case CXCursor_ClassDecl: return "ClassDecl";
1386 case CXCursor_FieldDecl: return "FieldDecl";
1387 case CXCursor_VarDecl: return "VarDecl";
1388 case CXCursor_ParmDecl: return "ParmDecl";
1389 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1390 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1391 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1392 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1393 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1394 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1395 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001396 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1397 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001398 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001399 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1400 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1401 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001402 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001403 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1404 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1405 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1406 case CXCursor_CallExpr: return "CallExpr";
1407 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1408 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001409 case CXCursor_InvalidFile: return "InvalidFile";
1410 case CXCursor_NoDeclFound: return "NoDeclFound";
1411 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001412 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001413 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001414
1415 llvm_unreachable("Unhandled CXCursorKind");
1416 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001417}
Steve Naroff89922f82009-08-31 00:59:03 +00001418
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001419enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1420 CXCursor parent,
1421 CXClientData client_data) {
1422 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1423 *BestCursor = cursor;
1424 return CXChildVisit_Recurse;
1425}
1426
Douglas Gregorb9790342010-01-22 21:44:22 +00001427CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1428 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001429 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001430
Douglas Gregorb9790342010-01-22 21:44:22 +00001431 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1432
Ted Kremeneka297de22010-01-25 22:34:44 +00001433 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001434 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1435 if (SLoc.isValid()) {
1436 SourceRange RegionOfInterest(SLoc,
1437 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1438
1439 // FIXME: Would be great to have a "hint" cursor, then walk from that
1440 // hint cursor upward until we find a cursor whose source range encloses
1441 // the region of interest, rather than starting from the translation unit.
1442 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1443 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1444 Decl::MaxPCHLevel, RegionOfInterest);
1445 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001446 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001447 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001448}
1449
Ted Kremenek73885552009-11-17 19:28:59 +00001450CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001451 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001452}
1453
1454unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001455 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001456}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001457
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001458unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001459 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1460}
1461
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001462unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001463 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1464}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001465
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001466unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001467 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1468}
1469
Douglas Gregor97b98722010-01-19 23:20:36 +00001470unsigned clang_isExpression(enum CXCursorKind K) {
1471 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1472}
1473
1474unsigned clang_isStatement(enum CXCursorKind K) {
1475 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1476}
1477
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001478unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1479 return K == CXCursor_TranslationUnit;
1480}
1481
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001482CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001483 return C.kind;
1484}
1485
Douglas Gregor97b98722010-01-19 23:20:36 +00001486static SourceLocation getLocationFromExpr(Expr *E) {
1487 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1488 return /*FIXME:*/Msg->getLeftLoc();
1489 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1490 return DRE->getLocation();
1491 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1492 return Member->getMemberLoc();
1493 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1494 return Ivar->getLocation();
1495 return E->getLocStart();
1496}
1497
Douglas Gregor98258af2010-01-18 22:46:11 +00001498CXSourceLocation clang_getCursorLocation(CXCursor C) {
1499 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001500 switch (C.kind) {
1501 case CXCursor_ObjCSuperClassRef: {
1502 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1503 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001504 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001505 }
1506
1507 case CXCursor_ObjCProtocolRef: {
1508 std::pair<ObjCProtocolDecl *, SourceLocation> P
1509 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001510 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001511 }
1512
1513 case CXCursor_ObjCClassRef: {
1514 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1515 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001516 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001517 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001518
1519 case CXCursor_TypeRef: {
1520 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001521 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001522 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001523
Douglas Gregorf46034a2010-01-18 23:41:10 +00001524 default:
1525 // FIXME: Need a way to enumerate all non-reference cases.
1526 llvm_unreachable("Missed a reference kind");
1527 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001528 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001529
1530 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001531 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001532 getLocationFromExpr(getCursorExpr(C)));
1533
Douglas Gregor5352ac02010-01-28 00:27:43 +00001534 if (!getCursorDecl(C))
1535 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001536
Douglas Gregorf46034a2010-01-18 23:41:10 +00001537 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001538 SourceLocation Loc = D->getLocation();
1539 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1540 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001541 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001542}
Douglas Gregora7bde202010-01-19 00:34:46 +00001543
1544CXSourceRange clang_getCursorExtent(CXCursor C) {
1545 if (clang_isReference(C.kind)) {
1546 switch (C.kind) {
1547 case CXCursor_ObjCSuperClassRef: {
1548 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1549 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001550 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001551 }
1552
1553 case CXCursor_ObjCProtocolRef: {
1554 std::pair<ObjCProtocolDecl *, SourceLocation> P
1555 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001556 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001557 }
1558
1559 case CXCursor_ObjCClassRef: {
1560 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1561 = getCursorObjCClassRef(C);
1562
Ted Kremeneka297de22010-01-25 22:34:44 +00001563 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001564 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001565
1566 case CXCursor_TypeRef: {
1567 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001568 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001569 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001570
Douglas Gregora7bde202010-01-19 00:34:46 +00001571 default:
1572 // FIXME: Need a way to enumerate all non-reference cases.
1573 llvm_unreachable("Missed a reference kind");
1574 }
1575 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001576
1577 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001578 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001579 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001580
1581 if (clang_isStatement(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001582 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001583 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001584
Douglas Gregor5352ac02010-01-28 00:27:43 +00001585 if (!getCursorDecl(C))
1586 return clang_getNullRange();
Douglas Gregora7bde202010-01-19 00:34:46 +00001587
1588 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001589 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001590}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001591
1592CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001593 if (clang_isInvalid(C.kind))
1594 return clang_getNullCursor();
1595
1596 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001597 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001598 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001599
Douglas Gregor97b98722010-01-19 23:20:36 +00001600 if (clang_isExpression(C.kind)) {
1601 Decl *D = getDeclFromExpr(getCursorExpr(C));
1602 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001603 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001604 return clang_getNullCursor();
1605 }
1606
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001607 if (!clang_isReference(C.kind))
1608 return clang_getNullCursor();
1609
1610 switch (C.kind) {
1611 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001612 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001613
1614 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001615 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001616
1617 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001618 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001619
1620 case CXCursor_TypeRef:
1621 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001622
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001623 default:
1624 // We would prefer to enumerate all non-reference cursor kinds here.
1625 llvm_unreachable("Unhandled reference cursor kind");
1626 break;
1627 }
1628 }
1629
1630 return clang_getNullCursor();
1631}
1632
Douglas Gregorb6998662010-01-19 19:34:47 +00001633CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001634 if (clang_isInvalid(C.kind))
1635 return clang_getNullCursor();
1636
1637 ASTUnit *CXXUnit = getCursorASTUnit(C);
1638
Douglas Gregorb6998662010-01-19 19:34:47 +00001639 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001640 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001641 C = clang_getCursorReferenced(C);
1642 WasReference = true;
1643 }
1644
1645 if (!clang_isDeclaration(C.kind))
1646 return clang_getNullCursor();
1647
1648 Decl *D = getCursorDecl(C);
1649 if (!D)
1650 return clang_getNullCursor();
1651
1652 switch (D->getKind()) {
1653 // Declaration kinds that don't really separate the notions of
1654 // declaration and definition.
1655 case Decl::Namespace:
1656 case Decl::Typedef:
1657 case Decl::TemplateTypeParm:
1658 case Decl::EnumConstant:
1659 case Decl::Field:
1660 case Decl::ObjCIvar:
1661 case Decl::ObjCAtDefsField:
1662 case Decl::ImplicitParam:
1663 case Decl::ParmVar:
1664 case Decl::NonTypeTemplateParm:
1665 case Decl::TemplateTemplateParm:
1666 case Decl::ObjCCategoryImpl:
1667 case Decl::ObjCImplementation:
1668 case Decl::LinkageSpec:
1669 case Decl::ObjCPropertyImpl:
1670 case Decl::FileScopeAsm:
1671 case Decl::StaticAssert:
1672 case Decl::Block:
1673 return C;
1674
1675 // Declaration kinds that don't make any sense here, but are
1676 // nonetheless harmless.
1677 case Decl::TranslationUnit:
1678 case Decl::Template:
1679 case Decl::ObjCContainer:
1680 break;
1681
1682 // Declaration kinds for which the definition is not resolvable.
1683 case Decl::UnresolvedUsingTypename:
1684 case Decl::UnresolvedUsingValue:
1685 break;
1686
1687 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001688 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1689 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001690
1691 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001692 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001693
1694 case Decl::Enum:
1695 case Decl::Record:
1696 case Decl::CXXRecord:
1697 case Decl::ClassTemplateSpecialization:
1698 case Decl::ClassTemplatePartialSpecialization:
1699 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001700 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001701 return clang_getNullCursor();
1702
1703 case Decl::Function:
1704 case Decl::CXXMethod:
1705 case Decl::CXXConstructor:
1706 case Decl::CXXDestructor:
1707 case Decl::CXXConversion: {
1708 const FunctionDecl *Def = 0;
1709 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001710 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001711 return clang_getNullCursor();
1712 }
1713
1714 case Decl::Var: {
1715 VarDecl *Var = cast<VarDecl>(D);
1716
1717 // Variables with initializers have definitions.
1718 const VarDecl *Def = 0;
1719 if (Var->getDefinition(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001720 return MakeCXCursor(const_cast<VarDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001721
1722 // extern and private_extern variables are not definitions.
1723 if (Var->hasExternalStorage())
1724 return clang_getNullCursor();
1725
1726 // In-line static data members do not have definitions.
1727 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1728 return clang_getNullCursor();
1729
1730 // All other variables are themselves definitions.
1731 return C;
1732 }
1733
1734 case Decl::FunctionTemplate: {
1735 const FunctionDecl *Def = 0;
1736 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001737 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001738 return clang_getNullCursor();
1739 }
1740
1741 case Decl::ClassTemplate: {
1742 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1743 ->getDefinition(D->getASTContext()))
1744 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001745 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1746 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001747 return clang_getNullCursor();
1748 }
1749
1750 case Decl::Using: {
1751 UsingDecl *Using = cast<UsingDecl>(D);
1752 CXCursor Def = clang_getNullCursor();
1753 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1754 SEnd = Using->shadow_end();
1755 S != SEnd; ++S) {
1756 if (Def != clang_getNullCursor()) {
1757 // FIXME: We have no way to return multiple results.
1758 return clang_getNullCursor();
1759 }
1760
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001761 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1762 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001763 }
1764
1765 return Def;
1766 }
1767
1768 case Decl::UsingShadow:
1769 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001770 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1771 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001772
1773 case Decl::ObjCMethod: {
1774 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1775 if (Method->isThisDeclarationADefinition())
1776 return C;
1777
1778 // Dig out the method definition in the associated
1779 // @implementation, if we have it.
1780 // FIXME: The ASTs should make finding the definition easier.
1781 if (ObjCInterfaceDecl *Class
1782 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1783 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1784 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1785 Method->isInstanceMethod()))
1786 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001787 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001788
1789 return clang_getNullCursor();
1790 }
1791
1792 case Decl::ObjCCategory:
1793 if (ObjCCategoryImplDecl *Impl
1794 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001795 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001796 return clang_getNullCursor();
1797
1798 case Decl::ObjCProtocol:
1799 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1800 return C;
1801 return clang_getNullCursor();
1802
1803 case Decl::ObjCInterface:
1804 // There are two notions of a "definition" for an Objective-C
1805 // class: the interface and its implementation. When we resolved a
1806 // reference to an Objective-C class, produce the @interface as
1807 // the definition; when we were provided with the interface,
1808 // produce the @implementation as the definition.
1809 if (WasReference) {
1810 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1811 return C;
1812 } else if (ObjCImplementationDecl *Impl
1813 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001814 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001815 return clang_getNullCursor();
1816
1817 case Decl::ObjCProperty:
1818 // FIXME: We don't really know where to find the
1819 // ObjCPropertyImplDecls that implement this property.
1820 return clang_getNullCursor();
1821
1822 case Decl::ObjCCompatibleAlias:
1823 if (ObjCInterfaceDecl *Class
1824 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1825 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001826 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001827
1828 return clang_getNullCursor();
1829
1830 case Decl::ObjCForwardProtocol: {
1831 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1832 if (Forward->protocol_size() == 1)
1833 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001834 MakeCXCursor(*Forward->protocol_begin(),
1835 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001836
1837 // FIXME: Cannot return multiple definitions.
1838 return clang_getNullCursor();
1839 }
1840
1841 case Decl::ObjCClass: {
1842 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1843 if (Class->size() == 1) {
1844 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1845 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001846 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001847 return clang_getNullCursor();
1848 }
1849
1850 // FIXME: Cannot return multiple definitions.
1851 return clang_getNullCursor();
1852 }
1853
1854 case Decl::Friend:
1855 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001856 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001857 return clang_getNullCursor();
1858
1859 case Decl::FriendTemplate:
1860 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001861 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001862 return clang_getNullCursor();
1863 }
1864
1865 return clang_getNullCursor();
1866}
1867
1868unsigned clang_isCursorDefinition(CXCursor C) {
1869 if (!clang_isDeclaration(C.kind))
1870 return 0;
1871
1872 return clang_getCursorDefinition(C) == C;
1873}
1874
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001875void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001876 const char **startBuf,
1877 const char **endBuf,
1878 unsigned *startLine,
1879 unsigned *startColumn,
1880 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001881 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001882 assert(getCursorDecl(C) && "CXCursor has null decl");
1883 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001884 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1885 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001886
Steve Naroff4ade6d62009-09-23 17:52:52 +00001887 SourceManager &SM = FD->getASTContext().getSourceManager();
1888 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1889 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1890 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1891 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1892 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1893 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1894}
Ted Kremenekfb480492010-01-13 21:46:36 +00001895
1896} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001897
Ted Kremenekfb480492010-01-13 21:46:36 +00001898//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001899// Token-based Operations.
1900//===----------------------------------------------------------------------===//
1901
1902/* CXToken layout:
1903 * int_data[0]: a CXTokenKind
1904 * int_data[1]: starting token location
1905 * int_data[2]: token length
1906 * int_data[3]: reserved
1907 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
1908 * otherwise unused.
1909 */
1910extern "C" {
1911
1912CXTokenKind clang_getTokenKind(CXToken CXTok) {
1913 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1914}
1915
1916CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1917 switch (clang_getTokenKind(CXTok)) {
1918 case CXToken_Identifier:
1919 case CXToken_Keyword:
1920 // We know we have an IdentifierInfo*, so use that.
1921 return CIndexer::createCXString(
1922 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
1923
1924 case CXToken_Literal: {
1925 // We have stashed the starting pointer in the ptr_data field. Use it.
1926 const char *Text = static_cast<const char *>(CXTok.ptr_data);
1927 return CIndexer::createCXString(llvm::StringRef(Text, CXTok.int_data[2]),
1928 true);
1929 }
1930
1931 case CXToken_Punctuation:
1932 case CXToken_Comment:
1933 break;
1934 }
1935
1936 // We have to find the starting buffer pointer the hard way, by
1937 // deconstructing the source location.
1938 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1939 if (!CXXUnit)
1940 return CIndexer::createCXString("");
1941
1942 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1943 std::pair<FileID, unsigned> LocInfo
1944 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1945 std::pair<const char *,const char *> Buffer
1946 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1947
1948 return CIndexer::createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1949 CXTok.int_data[2]),
1950 true);
1951}
1952
1953CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1954 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1955 if (!CXXUnit)
1956 return clang_getNullLocation();
1957
1958 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1959 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1960}
1961
1962CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1963 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001964 if (!CXXUnit)
1965 return clang_getNullRange();
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001966
1967 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
1968 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1969}
1970
1971void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1972 CXToken **Tokens, unsigned *NumTokens) {
1973 if (Tokens)
1974 *Tokens = 0;
1975 if (NumTokens)
1976 *NumTokens = 0;
1977
1978 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1979 if (!CXXUnit || !Tokens || !NumTokens)
1980 return;
1981
1982 SourceRange R = cxloc::translateSourceRange(Range);
1983 if (R.isInvalid())
1984 return;
1985
1986 SourceManager &SourceMgr = CXXUnit->getSourceManager();
1987 std::pair<FileID, unsigned> BeginLocInfo
1988 = SourceMgr.getDecomposedLoc(R.getBegin());
1989 std::pair<FileID, unsigned> EndLocInfo
1990 = SourceMgr.getDecomposedLoc(R.getEnd());
1991
1992 // Cannot tokenize across files.
1993 if (BeginLocInfo.first != EndLocInfo.first)
1994 return;
1995
1996 // Create a lexer
1997 std::pair<const char *,const char *> Buffer
1998 = SourceMgr.getBufferData(BeginLocInfo.first);
1999 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2000 CXXUnit->getASTContext().getLangOptions(),
2001 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
2002 Lex.SetCommentRetentionState(true);
2003
2004 // Lex tokens until we hit the end of the range.
2005 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
2006 llvm::SmallVector<CXToken, 32> CXTokens;
2007 Token Tok;
2008 do {
2009 // Lex the next token
2010 Lex.LexFromRawLexer(Tok);
2011 if (Tok.is(tok::eof))
2012 break;
2013
2014 // Initialize the CXToken.
2015 CXToken CXTok;
2016
2017 // - Common fields
2018 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2019 CXTok.int_data[2] = Tok.getLength();
2020 CXTok.int_data[3] = 0;
2021
2022 // - Kind-specific fields
2023 if (Tok.isLiteral()) {
2024 CXTok.int_data[0] = CXToken_Literal;
2025 CXTok.ptr_data = (void *)Tok.getLiteralData();
2026 } else if (Tok.is(tok::identifier)) {
2027 // Lookup the identifier to determine whether we have a
2028 std::pair<FileID, unsigned> LocInfo
2029 = SourceMgr.getDecomposedLoc(Tok.getLocation());
2030 const char *StartPos
2031 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
2032 LocInfo.second;
2033 IdentifierInfo *II
2034 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2035 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2036 CXToken_Identifier
2037 : CXToken_Keyword;
2038 CXTok.ptr_data = II;
2039 } else if (Tok.is(tok::comment)) {
2040 CXTok.int_data[0] = CXToken_Comment;
2041 CXTok.ptr_data = 0;
2042 } else {
2043 CXTok.int_data[0] = CXToken_Punctuation;
2044 CXTok.ptr_data = 0;
2045 }
2046 CXTokens.push_back(CXTok);
2047 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2048
2049 if (CXTokens.empty())
2050 return;
2051
2052 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2053 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2054 *NumTokens = CXTokens.size();
2055}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002056
2057typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2058
2059enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2060 CXCursor parent,
2061 CXClientData client_data) {
2062 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2063
2064 // We only annotate the locations of declarations, simple
2065 // references, and expressions which directly reference something.
2066 CXCursorKind Kind = clang_getCursorKind(cursor);
2067 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2068 // Okay: We can annotate the location of this declaration with the
2069 // declaration or reference
2070 } else if (clang_isExpression(cursor.kind)) {
2071 if (Kind != CXCursor_DeclRefExpr &&
2072 Kind != CXCursor_MemberRefExpr &&
2073 Kind != CXCursor_ObjCMessageExpr)
2074 return CXChildVisit_Recurse;
2075
2076 CXCursor Referenced = clang_getCursorReferenced(cursor);
2077 if (Referenced == cursor || Referenced == clang_getNullCursor())
2078 return CXChildVisit_Recurse;
2079
2080 // Okay: we can annotate the location of this expression
2081 } else {
2082 // Nothing to annotate
2083 return CXChildVisit_Recurse;
2084 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002085
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002086 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2087 (*Data)[Loc.int_data] = cursor;
2088 return CXChildVisit_Recurse;
2089}
2090
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002091void clang_annotateTokens(CXTranslationUnit TU,
2092 CXToken *Tokens, unsigned NumTokens,
2093 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002094 if (NumTokens == 0)
2095 return;
2096
2097 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002098 for (unsigned I = 0; I != NumTokens; ++I)
2099 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002100
2101 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2102 if (!CXXUnit || !Tokens)
2103 return;
2104
2105 // Annotate all of the source locations in the region of interest that map
2106 SourceRange RegionOfInterest;
2107 RegionOfInterest.setBegin(
2108 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2109 SourceLocation End
2110 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2111 Tokens[NumTokens - 1]));
2112 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End,
2113 1));
2114 // FIXME: Would be great to have a "hint" cursor, then walk from that
2115 // hint cursor upward until we find a cursor whose source range encloses
2116 // the region of interest, rather than starting from the translation unit.
2117 AnnotateTokensData Annotated;
2118 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2119 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2120 Decl::MaxPCHLevel, RegionOfInterest);
2121 AnnotateVis.VisitChildren(Parent);
2122
2123 for (unsigned I = 0; I != NumTokens; ++I) {
2124 // Determine whether we saw a cursor at this token's location.
2125 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2126 if (Pos == Annotated.end())
2127 continue;
2128
2129 Cursors[I] = Pos->second;
2130 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002131}
2132
2133void clang_disposeTokens(CXTranslationUnit TU,
2134 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002135 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002136}
2137
2138} // end: extern "C"
2139
2140//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002141// CXString Operations.
2142//===----------------------------------------------------------------------===//
2143
2144extern "C" {
2145const char *clang_getCString(CXString string) {
2146 return string.Spelling;
2147}
2148
2149void clang_disposeString(CXString string) {
2150 if (string.MustFreeString && string.Spelling)
2151 free((void*)string.Spelling);
2152}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002153
Ted Kremenekfb480492010-01-13 21:46:36 +00002154} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002155
2156//===----------------------------------------------------------------------===//
2157// Misc. utility functions.
2158//===----------------------------------------------------------------------===//
2159
2160extern "C" {
2161
2162const char *clang_getClangVersion() {
Ted Kremeneka18f1b82010-01-23 02:11:34 +00002163 return getClangFullVersion();
Ted Kremenek04bb7162010-01-22 22:44:15 +00002164}
2165
2166} // end: extern "C"
2167