blob: 336a638b3aa9a26dad6d6f8c5b604c00ab2e1366 [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"
Steve Naroff50398192009-08-28 15:28:48 +000021#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000022#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000023#include "clang/AST/TypeLocVisitor.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000024#include "clang/Lex/Lexer.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000025#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000026#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000027#include "llvm/System/Program.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000028
Ted Kremenekdb3d0da2010-01-05 20:55:39 +000029// Needed to define L_TMPNAM on some systems.
30#include <cstdio>
31
Steve Naroff50398192009-08-28 15:28:48 +000032using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000033using namespace clang::cxcursor;
Steve Naroff50398192009-08-28 15:28:48 +000034using namespace idx;
35
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000036//===----------------------------------------------------------------------===//
37// Crash Reporting.
38//===----------------------------------------------------------------------===//
39
40#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000041#ifndef NDEBUG
42#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000043#include "clang/Analysis/Support/SaveAndRestore.h"
44// Integrate with crash reporter.
45extern "C" const char *__crashreporter_info__;
Ted Kremenek29b72842010-01-07 22:49:05 +000046#define NUM_CRASH_STRINGS 16
47static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000048static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000049static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
50static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
51
52static unsigned SetCrashTracerInfo(const char *str,
53 llvm::SmallString<1024> &AggStr) {
54
Ted Kremenek254ba7c2010-01-07 23:13:53 +000055 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000056 while (crashtracer_strings[slot]) {
57 if (++slot == NUM_CRASH_STRINGS)
58 slot = 0;
59 }
60 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000061 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000062
63 // We need to create an aggregate string because multiple threads
64 // may be in this method at one time. The crash reporter string
65 // will attempt to overapproximate the set of in-flight invocations
66 // of this function. Race conditions can still cause this goal
67 // to not be achieved.
68 {
69 llvm::raw_svector_ostream Out(AggStr);
70 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
71 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
72 }
73 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
74 return slot;
75}
76
77static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000078 unsigned max_slot = 0;
79 unsigned max_value = 0;
80
81 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
82
83 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
84 if (agg_crashtracer_strings[i] &&
85 crashtracer_counter_id[i] > max_value) {
86 max_slot = i;
87 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000088 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000089
90 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000091}
92
93namespace {
94class ArgsCrashTracerInfo {
95 llvm::SmallString<1024> CrashString;
96 llvm::SmallString<1024> AggregateString;
97 unsigned crashtracerSlot;
98public:
99 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
100 : crashtracerSlot(0)
101 {
102 {
103 llvm::raw_svector_ostream Out(CrashString);
104 Out << "ClangCIndex [createTranslationUnitFromSourceFile]: clang";
105 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
106 E=Args.end(); I!=E; ++I)
107 Out << ' ' << *I;
108 }
109 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
110 AggregateString);
111 }
112
113 ~ArgsCrashTracerInfo() {
114 ResetCrashTracerInfo(crashtracerSlot);
115 }
116};
117}
118#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000119#endif
120
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000121/// \brief The result of comparing two source ranges.
122enum RangeComparisonResult {
123 /// \brief Either the ranges overlap or one of the ranges is invalid.
124 RangeOverlap,
125
126 /// \brief The first range ends before the second range starts.
127 RangeBefore,
128
129 /// \brief The first range starts after the second range ends.
130 RangeAfter
131};
132
133/// \brief Compare two source ranges to determine their relative position in
134/// the translation unit.
135static RangeComparisonResult RangeCompare(SourceManager &SM,
136 SourceRange R1,
137 SourceRange R2) {
138 assert(R1.isValid() && "First range is invalid?");
139 assert(R2.isValid() && "Second range is invalid?");
140 if (SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
141 return RangeBefore;
142 if (SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
143 return RangeAfter;
144 return RangeOverlap;
145}
146
Douglas Gregor1db19de2010-01-19 21:36:55 +0000147
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000148//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000149// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000150//===----------------------------------------------------------------------===//
151
Steve Naroff89922f82009-08-31 00:59:03 +0000152namespace {
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000153
Douglas Gregorb1373d02010-01-20 20:59:29 +0000154// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000155class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000156 public TypeLocVisitor<CursorVisitor, bool>,
157 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000158{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000159 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000160 ASTUnit *TU;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000161
162 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000163 CXCursor Parent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000164
165 /// \brief The declaration that serves at the parent of any statement or
166 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000167 Decl *StmtParent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000168
169 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000170 CXCursorVisitor Visitor;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000171
172 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000173 CXClientData ClientData;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000174
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000175 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
176 // to the visitor. Declarations with a PCH level greater than this value will
177 // be suppressed.
178 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000179
180 /// \brief When valid, a source range to which the cursor should restrict
181 /// its search.
182 SourceRange RegionOfInterest;
183
Douglas Gregorb1373d02010-01-20 20:59:29 +0000184 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000185 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000186 using StmtVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000187
188 /// \brief Determine whether this particular source range comes before, comes
189 /// after, or overlaps the region of interest.
190 ///
191 /// \param R a source range retrieved from the abstract syntax tree.
192 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
193
194 /// \brief Determine whether this particular source range comes before, comes
195 /// after, or overlaps the region of interest.
196 ///
197 /// \param CXR a source range retrieved from a cursor.
198 RangeComparisonResult CompareRegionOfInterest(CXSourceRange CXR);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000199
Steve Naroff89922f82009-08-31 00:59:03 +0000200public:
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000201 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000202 unsigned MaxPCHLevel,
203 SourceRange RegionOfInterest = SourceRange())
204 : TU(TU), Visitor(Visitor), ClientData(ClientData),
205 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000206 {
207 Parent.kind = CXCursor_NoDeclFound;
208 Parent.data[0] = 0;
209 Parent.data[1] = 0;
210 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000211 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000212 }
213
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000214 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000215 bool VisitChildren(CXCursor Parent);
216
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000217 // Declaration visitors
Douglas Gregorb1373d02010-01-20 20:59:29 +0000218 bool VisitDeclContext(DeclContext *DC);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000219 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000220 bool VisitTypedefDecl(TypedefDecl *D);
221 bool VisitTagDecl(TagDecl *D);
222 bool VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000223 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000224 bool VisitFunctionDecl(FunctionDecl *ND);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000225 bool VisitFieldDecl(FieldDecl *D);
226 bool VisitVarDecl(VarDecl *);
227 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
Douglas Gregora59e3902010-01-21 23:27:09 +0000228 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000229 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000230 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000231 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
232 bool VisitObjCImplDecl(ObjCImplDecl *D);
233 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
234 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
235 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
236 // etc.
237 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
238 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
239 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000240
241 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000242 // FIXME: QualifiedTypeLoc doesn't provide any location information
243 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000244 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000245 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
246 bool VisitTagTypeLoc(TagTypeLoc TL);
247 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
248 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
249 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
250 bool VisitPointerTypeLoc(PointerTypeLoc TL);
251 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
252 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
253 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
254 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
255 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
256 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000257 // FIXME: Implement for TemplateSpecializationTypeLoc
258 // FIXME: Implement visitors here when the unimplemented TypeLocs get
259 // implemented
260 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
261 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregora59e3902010-01-21 23:27:09 +0000262
263 // Statement visitors
264 bool VisitStmt(Stmt *S);
265 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000266 // FIXME: LabelStmt label?
267 bool VisitIfStmt(IfStmt *S);
268 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000269 bool VisitWhileStmt(WhileStmt *S);
270 bool VisitForStmt(ForStmt *S);
Douglas Gregor336fd812010-01-23 00:40:08 +0000271
272 // Expression visitors
273 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
274 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
275 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000276};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000277
Ted Kremenekab188932010-01-05 19:32:54 +0000278} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000279
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000280RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
281 assert(RegionOfInterest.isValid() && "RangeCompare called with invalid range");
282 if (R.isInvalid())
283 return RangeOverlap;
284
285 // Move the end of the input range to the end of the last token in that
286 // range.
287 R.setEnd(TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1));
288 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
289}
290
291RangeComparisonResult CursorVisitor::CompareRegionOfInterest(CXSourceRange CXR) {
Ted Kremeneka297de22010-01-25 22:34:44 +0000292 return CompareRegionOfInterest(cxloc::translateSourceRange(CXR));
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000293}
294
Douglas Gregorb1373d02010-01-20 20:59:29 +0000295/// \brief Visit the given cursor and, if requested by the visitor,
296/// its children.
297///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000298/// \param Cursor the cursor to visit.
299///
300/// \param CheckRegionOfInterest if true, then the caller already checked that
301/// this cursor is within the region of interest.
302///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000303/// \returns true if the visitation should be aborted, false if it
304/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000305bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000306 if (clang_isInvalid(Cursor.kind))
307 return false;
308
309 if (clang_isDeclaration(Cursor.kind)) {
310 Decl *D = getCursorDecl(Cursor);
311 assert(D && "Invalid declaration cursor");
312 if (D->getPCHLevel() > MaxPCHLevel)
313 return false;
314
315 if (D->isImplicit())
316 return false;
317 }
318
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000319 // If we have a range of interest, and this cursor doesn't intersect with it,
320 // we're done.
321 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
322 CXSourceRange Range = clang_getCursorExtent(Cursor);
Ted Kremeneka297de22010-01-25 22:34:44 +0000323 if (cxloc::translateSourceRange(Range).isInvalid() ||
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000324 CompareRegionOfInterest(Range))
325 return false;
326 }
327
Douglas Gregorb1373d02010-01-20 20:59:29 +0000328 switch (Visitor(Cursor, Parent, ClientData)) {
329 case CXChildVisit_Break:
330 return true;
331
332 case CXChildVisit_Continue:
333 return false;
334
335 case CXChildVisit_Recurse:
336 return VisitChildren(Cursor);
337 }
338
Douglas Gregorfd643772010-01-25 16:45:46 +0000339 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000340}
341
342/// \brief Visit the children of the given cursor.
343///
344/// \returns true if the visitation should be aborted, false if it
345/// should continue.
346bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000347 if (clang_isReference(Cursor.kind)) {
348 // By definition, references have no children.
349 return false;
350 }
351
Douglas Gregorb1373d02010-01-20 20:59:29 +0000352 // Set the Parent field to Cursor, then back to its old value once we're
353 // done.
354 class SetParentRAII {
355 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000356 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000357 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000358
Douglas Gregorb1373d02010-01-20 20:59:29 +0000359 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000360 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
361 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000362 {
363 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000364 if (clang_isDeclaration(Parent.kind))
365 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000366 }
367
368 ~SetParentRAII() {
369 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000370 if (clang_isDeclaration(Parent.kind))
371 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000373 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374
375 if (clang_isDeclaration(Cursor.kind)) {
376 Decl *D = getCursorDecl(Cursor);
377 assert(D && "Invalid declaration cursor");
378 return Visit(D);
379 }
380
Douglas Gregora59e3902010-01-21 23:27:09 +0000381 if (clang_isStatement(Cursor.kind))
382 return Visit(getCursorStmt(Cursor));
383 if (clang_isExpression(Cursor.kind))
384 return Visit(getCursorExpr(Cursor));
385
Douglas Gregorb1373d02010-01-20 20:59:29 +0000386 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000387 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000388 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
389 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000390 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
391 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
392 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000393 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000394 return true;
395 }
396 } else {
397 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000398 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000399 }
400
401 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000402 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000403
Douglas Gregorb1373d02010-01-20 20:59:29 +0000404 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000405 return false;
406}
407
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000409 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000410 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000411 if (RegionOfInterest.isValid()) {
412 SourceRange R = (*I)->getSourceRange();
413 if (R.isInvalid())
414 continue;
415
416 switch (CompareRegionOfInterest(R)) {
417 case RangeBefore:
418 // This declaration comes before the region of interest; skip it.
419 continue;
420
421 case RangeAfter:
422 // This declaration comes after the region of interest; we're done.
423 return false;
424
425 case RangeOverlap:
426 // This declaration overlaps the region of interest; visit it.
427 break;
428 }
429 }
430
431 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000432 return true;
433 }
434
435 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000436}
437
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000438bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
439 llvm_unreachable("Translation units are visited directly by Visit()");
440 return false;
441}
442
443bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
444 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
445 return Visit(TSInfo->getTypeLoc());
446
447 return false;
448}
449
450bool CursorVisitor::VisitTagDecl(TagDecl *D) {
451 return VisitDeclContext(D);
452}
453
454bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
455 if (Expr *Init = D->getInitExpr())
456 return Visit(MakeCXCursor(Init, StmtParent, TU));
457 return false;
458}
459
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000460bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
461 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
462 if (Visit(TSInfo->getTypeLoc()))
463 return true;
464
465 return false;
466}
467
Douglas Gregorb1373d02010-01-20 20:59:29 +0000468bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000469 if (VisitDeclaratorDecl(ND))
470 return true;
471
Douglas Gregora59e3902010-01-21 23:27:09 +0000472 if (ND->isThisDeclarationADefinition() &&
473 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
474 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000475
476 return false;
477}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000478
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000479bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
480 if (VisitDeclaratorDecl(D))
481 return true;
482
483 if (Expr *BitWidth = D->getBitWidth())
484 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
485
486 return false;
487}
488
489bool CursorVisitor::VisitVarDecl(VarDecl *D) {
490 if (VisitDeclaratorDecl(D))
491 return true;
492
493 if (Expr *Init = D->getInit())
494 return Visit(MakeCXCursor(Init, StmtParent, TU));
495
496 return false;
497}
498
499bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
500 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
501 // At the moment, we don't have information about locations in the return
502 // type.
503 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
504 PEnd = ND->param_end();
505 P != PEnd; ++P) {
506 if (Visit(MakeCXCursor(*P, TU)))
507 return true;
508 }
509
510 if (ND->isThisDeclarationADefinition() &&
511 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
512 return true;
513
514 return false;
515}
516
Douglas Gregora59e3902010-01-21 23:27:09 +0000517bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
518 return VisitDeclContext(D);
519}
520
Douglas Gregorb1373d02010-01-20 20:59:29 +0000521bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000522 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
523 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000524 return true;
525
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000526 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
527 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
528 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000529 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000530 return true;
531
Douglas Gregora59e3902010-01-21 23:27:09 +0000532 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000533}
534
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000535bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
536 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
537 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
538 E = PID->protocol_end(); I != E; ++I, ++PL)
539 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
540 return true;
541
542 return VisitObjCContainerDecl(PID);
543}
544
Douglas Gregorb1373d02010-01-20 20:59:29 +0000545bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000546 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000547 if (D->getSuperClass() &&
548 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000549 D->getSuperClassLoc(),
550 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000551 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000552
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000553 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
554 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
555 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000556 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000557 return true;
558
Douglas Gregora59e3902010-01-21 23:27:09 +0000559 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000560}
561
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000562bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
563 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000564}
565
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000566bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
567 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
568 D->getLocation(), TU)))
569 return true;
570
571 return VisitObjCImplDecl(D);
572}
573
574bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
575#if 0
576 // Issue callbacks for super class.
577 // FIXME: No source location information!
578 if (D->getSuperClass() &&
579 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
580 D->getSuperClassLoc(),
581 TU)))
582 return true;
583#endif
584
585 return VisitObjCImplDecl(D);
586}
587
588bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
589 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
590 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
591 E = D->protocol_end();
592 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000593 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000594 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000595
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000596 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000597}
598
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000599bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
600 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
601 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
602 return true;
603
604 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000605}
606
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000607bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
608 ASTContext &Context = TU->getASTContext();
609
610 // Some builtin types (such as Objective-C's "id", "sel", and
611 // "Class") have associated declarations. Create cursors for those.
612 QualType VisitType;
613 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
614 case BuiltinType::Void:
615 case BuiltinType::Bool:
616 case BuiltinType::Char_U:
617 case BuiltinType::UChar:
618 case BuiltinType::Char16:
619 case BuiltinType::Char32:
620 case BuiltinType::UShort:
621 case BuiltinType::UInt:
622 case BuiltinType::ULong:
623 case BuiltinType::ULongLong:
624 case BuiltinType::UInt128:
625 case BuiltinType::Char_S:
626 case BuiltinType::SChar:
627 case BuiltinType::WChar:
628 case BuiltinType::Short:
629 case BuiltinType::Int:
630 case BuiltinType::Long:
631 case BuiltinType::LongLong:
632 case BuiltinType::Int128:
633 case BuiltinType::Float:
634 case BuiltinType::Double:
635 case BuiltinType::LongDouble:
636 case BuiltinType::NullPtr:
637 case BuiltinType::Overload:
638 case BuiltinType::Dependent:
639 break;
640
641 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
642 break;
643
644 case BuiltinType::ObjCId:
645 VisitType = Context.getObjCIdType();
646 break;
647
648 case BuiltinType::ObjCClass:
649 VisitType = Context.getObjCClassType();
650 break;
651
652 case BuiltinType::ObjCSel:
653 VisitType = Context.getObjCSelType();
654 break;
655 }
656
657 if (!VisitType.isNull()) {
658 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
659 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
660 TU));
661 }
662
663 return false;
664}
665
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000666bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
667 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
668}
669
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000670bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
671 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
672}
673
674bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
675 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
676}
677
678bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
679 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
680 return true;
681
682 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
683 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
684 TU)))
685 return true;
686 }
687
688 return false;
689}
690
691bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
692 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
693 return true;
694
695 if (TL.hasProtocolsAsWritten()) {
696 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
697 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
698 TL.getProtocolLoc(I),
699 TU)))
700 return true;
701 }
702 }
703
704 return false;
705}
706
707bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
708 return Visit(TL.getPointeeLoc());
709}
710
711bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
712 return Visit(TL.getPointeeLoc());
713}
714
715bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
716 return Visit(TL.getPointeeLoc());
717}
718
719bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
720 return Visit(TL.getPointeeLoc());
721}
722
723bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
724 return Visit(TL.getPointeeLoc());
725}
726
727bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
728 if (Visit(TL.getResultLoc()))
729 return true;
730
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000731 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
732 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
733 return true;
734
735 return false;
736}
737
738bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
739 if (Visit(TL.getElementLoc()))
740 return true;
741
742 if (Expr *Size = TL.getSizeExpr())
743 return Visit(MakeCXCursor(Size, StmtParent, TU));
744
745 return false;
746}
747
Douglas Gregor2332c112010-01-21 20:48:56 +0000748bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
749 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
750}
751
752bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
753 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
754 return Visit(TSInfo->getTypeLoc());
755
756 return false;
757}
758
Douglas Gregora59e3902010-01-21 23:27:09 +0000759bool CursorVisitor::VisitStmt(Stmt *S) {
760 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
761 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000762 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000763 return true;
764 }
765
766 return false;
767}
768
769bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
770 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
771 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000772 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000773 return true;
774 }
775
776 return false;
777}
778
Douglas Gregorf5bab412010-01-22 01:00:11 +0000779bool CursorVisitor::VisitIfStmt(IfStmt *S) {
780 if (VarDecl *Var = S->getConditionVariable()) {
781 if (Visit(MakeCXCursor(Var, TU)))
782 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000783 }
Douglas Gregorf5bab412010-01-22 01:00:11 +0000784
Douglas Gregor263b47b2010-01-25 16:12:32 +0000785 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
786 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000787 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
788 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000789 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
790 return true;
791
792 return false;
793}
794
795bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
796 if (VarDecl *Var = S->getConditionVariable()) {
797 if (Visit(MakeCXCursor(Var, TU)))
798 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000799 }
800
801 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
802 return true;
803 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
804 return true;
805
806 return false;
807}
808
809bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
810 if (VarDecl *Var = S->getConditionVariable()) {
811 if (Visit(MakeCXCursor(Var, TU)))
812 return true;
813 }
814
815 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
816 return true;
817 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000818 return true;
819
Douglas Gregor263b47b2010-01-25 16:12:32 +0000820 return false;
821}
822
823bool CursorVisitor::VisitForStmt(ForStmt *S) {
824 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
825 return true;
826 if (VarDecl *Var = S->getConditionVariable()) {
827 if (Visit(MakeCXCursor(Var, TU)))
828 return true;
829 }
830
831 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
832 return true;
833 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
834 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000835 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
836 return true;
837
838 return false;
839}
840
Douglas Gregor336fd812010-01-23 00:40:08 +0000841bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
842 if (E->isArgumentType()) {
843 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
844 return Visit(TSInfo->getTypeLoc());
845
846 return false;
847 }
848
849 return VisitExpr(E);
850}
851
852bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
853 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
854 if (Visit(TSInfo->getTypeLoc()))
855 return true;
856
857 return VisitCastExpr(E);
858}
859
860bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
861 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
862 if (Visit(TSInfo->getTypeLoc()))
863 return true;
864
865 return VisitExpr(E);
866}
867
Daniel Dunbar140fce22010-01-12 02:34:07 +0000868CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000869 CXString Str;
870 if (DupString) {
871 Str.Spelling = strdup(String);
872 Str.MustFreeString = 1;
873 } else {
874 Str.Spelling = String;
875 Str.MustFreeString = 0;
876 }
877 return Str;
878}
879
Douglas Gregorfc8ea232010-01-26 17:06:03 +0000880CXString CIndexer::createCXString(llvm::StringRef String, bool DupString) {
881 CXString Result;
882 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
883 char *Spelling = (char *)malloc(String.size() + 1);
884 memmove(Spelling, String.data(), String.size());
885 Spelling[String.size()] = 0;
886 Result.Spelling = Spelling;
887 Result.MustFreeString = 1;
888 } else {
889 Result.Spelling = String.data();
890 Result.MustFreeString = 0;
891 }
892 return Result;
893}
894
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000895extern "C" {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000896CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000897 int displayDiagnostics) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000898 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000899 if (excludeDeclarationsFromPCH)
900 CIdxr->setOnlyLocalDecls();
901 if (displayDiagnostics)
902 CIdxr->setDisplayDiagnostics();
903 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000904}
905
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000906void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000907 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000908 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000909}
910
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000911void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
912 assert(CIdx && "Passed null CXIndex");
913 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
914 CXXIdx->setUseExternalASTGeneration(value);
915}
916
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000917CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000918 const char *ast_filename,
919 CXDiagnosticCallback diag_callback,
920 CXClientData diag_client_data) {
Steve Naroff50398192009-08-28 15:28:48 +0000921 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000922 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000923
Douglas Gregor5352ac02010-01-28 00:27:43 +0000924 // Configure the diagnostics.
925 DiagnosticOptions DiagOpts;
926 llvm::OwningPtr<Diagnostic> Diags;
927 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
928 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
929 Diags->setClient(&DiagClient);
930
931 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000932 CXXIdx->getOnlyLocalDecls(),
933 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000934}
935
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000936CXTranslationUnit
937clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
938 const char *source_filename,
939 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000940 const char **command_line_args,
941 unsigned num_unsaved_files,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000942 struct CXUnsavedFile *unsaved_files,
943 CXDiagnosticCallback diag_callback,
944 CXClientData diag_client_data) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000945 assert(CIdx && "Passed null CXIndex");
946 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
947
Douglas Gregor5352ac02010-01-28 00:27:43 +0000948 // Configure the diagnostics.
949 DiagnosticOptions DiagOpts;
950 llvm::OwningPtr<Diagnostic> Diags;
951 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
952 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
953 Diags->setClient(&DiagClient);
954
Douglas Gregor4db64a42010-01-23 00:14:00 +0000955 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
956 for (unsigned I = 0; I != num_unsaved_files; ++I) {
957 const llvm::MemoryBuffer *Buffer
958 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
959 unsaved_files[I].Contents + unsaved_files[I].Length,
960 unsaved_files[I].Filename);
961 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
962 Buffer));
963 }
964
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000965 if (!CXXIdx->getUseExternalASTGeneration()) {
966 llvm::SmallVector<const char *, 16> Args;
967
968 // The 'source_filename' argument is optional. If the caller does not
969 // specify it then it is assumed that the source file is specified
970 // in the actual argument list.
971 if (source_filename)
972 Args.push_back(source_filename);
973 Args.insert(Args.end(), command_line_args,
974 command_line_args + num_command_line_args);
975
Douglas Gregor5352ac02010-01-28 00:27:43 +0000976 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000977
Ted Kremenek29b72842010-01-07 22:49:05 +0000978#ifdef USE_CRASHTRACER
979 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000980#endif
981
Daniel Dunbar94220972009-12-05 02:17:18 +0000982 llvm::OwningPtr<ASTUnit> Unit(
983 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor5352ac02010-01-28 00:27:43 +0000984 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +0000985 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000986 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +0000987 /* UseBumpAllocator = */ true,
988 RemappedFiles.data(),
989 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +0000990
Daniel Dunbar94220972009-12-05 02:17:18 +0000991 // FIXME: Until we have broader testing, just drop the entire AST if we
992 // encountered an error.
Douglas Gregor5352ac02010-01-28 00:27:43 +0000993 if (NumErrors != Diags->getNumErrors())
Daniel Dunbar94220972009-12-05 02:17:18 +0000994 return 0;
995
996 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000997 }
998
Ted Kremenek139ba862009-10-22 00:03:57 +0000999 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001000 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001001
Ted Kremenek139ba862009-10-22 00:03:57 +00001002 // First add the complete path to the 'clang' executable.
1003 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001004 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001005
Ted Kremenek139ba862009-10-22 00:03:57 +00001006 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001007 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001008
Ted Kremenek139ba862009-10-22 00:03:57 +00001009 // The 'source_filename' argument is optional. If the caller does not
1010 // specify it then it is assumed that the source file is specified
1011 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001012 if (source_filename)
1013 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001014
Steve Naroff37b5ac22009-10-15 20:50:09 +00001015 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001016 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +00001017 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +00001018 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001019
Douglas Gregor4db64a42010-01-23 00:14:00 +00001020 // Remap any unsaved files to temporary files.
1021 std::vector<llvm::sys::Path> TemporaryFiles;
1022 std::vector<std::string> RemapArgs;
1023 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1024 return 0;
1025
1026 // The pointers into the elements of RemapArgs are stable because we
1027 // won't be adding anything to RemapArgs after this point.
1028 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1029 argv.push_back(RemapArgs[i].c_str());
1030
Ted Kremenek139ba862009-10-22 00:03:57 +00001031 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1032 for (int i = 0; i < num_command_line_args; ++i)
1033 if (const char *arg = command_line_args[i]) {
1034 if (strcmp(arg, "-o") == 0) {
1035 ++i; // Also skip the matching argument.
1036 continue;
1037 }
1038 if (strcmp(arg, "-emit-ast") == 0 ||
1039 strcmp(arg, "-c") == 0 ||
1040 strcmp(arg, "-fsyntax-only") == 0) {
1041 continue;
1042 }
1043
1044 // Keep the argument.
1045 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001046 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001047
Ted Kremenek139ba862009-10-22 00:03:57 +00001048 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001049 argv.push_back(NULL);
1050
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001051 // Invoke 'clang'.
1052 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1053 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001054 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +00001055 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001056 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
1057 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
1058 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001059
Ted Kremenek0854d702009-11-10 19:18:52 +00001060 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001061 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +00001062 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +00001063 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +00001064 I!=E; ++I) {
1065 if (*I)
1066 llvm::errs() << ' ' << *I << '\n';
1067 }
1068 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +00001069 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001070
Douglas Gregor5352ac02010-01-28 00:27:43 +00001071 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001072 CXXIdx->getOnlyLocalDecls(),
1073 /* UseBumpAllocator = */ true,
1074 RemappedFiles.data(),
1075 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001076 if (ATU)
1077 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001078
1079 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1080 TemporaryFiles[i].eraseFromDisk();
1081
Steve Naroffe19944c2009-10-15 22:23:48 +00001082 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001083}
1084
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001085void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001086 assert(CTUnit && "Passed null CXTranslationUnit");
1087 delete static_cast<ASTUnit *>(CTUnit);
1088}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001089
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001090CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001091 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +00001092 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001093 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1094 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001095}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001096
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001097CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001098 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001099 return Result;
1100}
1101
Ted Kremenekfb480492010-01-13 21:46:36 +00001102} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001103
Ted Kremenekfb480492010-01-13 21:46:36 +00001104//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001105// CXSourceLocation and CXSourceRange Operations.
1106//===----------------------------------------------------------------------===//
1107
Douglas Gregorb9790342010-01-22 21:44:22 +00001108extern "C" {
1109CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001110 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001111 return Result;
1112}
1113
1114unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
1115 return loc1.ptr_data == loc2.ptr_data && loc1.int_data == loc2.int_data;
1116}
1117
1118CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1119 CXFile file,
1120 unsigned line,
1121 unsigned column) {
1122 if (!tu)
1123 return clang_getNullLocation();
1124
1125 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1126 SourceLocation SLoc
1127 = CXXUnit->getSourceManager().getLocation(
1128 static_cast<const FileEntry *>(file),
1129 line, column);
1130
Ted Kremeneka297de22010-01-25 22:34:44 +00001131 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc, false);
Douglas Gregorb9790342010-01-22 21:44:22 +00001132}
1133
Douglas Gregor5352ac02010-01-28 00:27:43 +00001134CXSourceRange clang_getNullRange() {
1135 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1136 return Result;
1137}
Douglas Gregorb9790342010-01-22 21:44:22 +00001138
Douglas Gregor5352ac02010-01-28 00:27:43 +00001139CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1140 if (begin.ptr_data[0] != end.ptr_data[0] ||
1141 begin.ptr_data[1] != end.ptr_data[1])
1142 return clang_getNullRange();
1143
1144 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1145 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001146 return Result;
1147}
1148
Douglas Gregor46766dc2010-01-26 19:19:08 +00001149void clang_getInstantiationLocation(CXSourceLocation location,
1150 CXFile *file,
1151 unsigned *line,
1152 unsigned *column,
1153 unsigned *offset) {
Ted Kremeneka297de22010-01-25 22:34:44 +00001154 cxloc::CXSourceLocationPtr Ptr
Douglas Gregor5352ac02010-01-28 00:27:43 +00001155 = cxloc::CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001156 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1157
Douglas Gregor46766dc2010-01-26 19:19:08 +00001158 if (!Ptr.getPointer() || Loc.isInvalid()) {
1159 if (file)
1160 *file = 0;
1161 if (line)
1162 *line = 0;
1163 if (column)
1164 *column = 0;
1165 if (offset)
1166 *offset = 0;
1167 return;
1168 }
1169
Douglas Gregor1db19de2010-01-19 21:36:55 +00001170 // FIXME: This is largely copy-paste from
1171 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
1172 // what we want the two routines should be refactored.
Douglas Gregor5352ac02010-01-28 00:27:43 +00001173 const SourceManager &SM = *Ptr.getPointer();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001174 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1175
1176 if (Ptr.getInt()) {
1177 // We want the last character in this location, so we will adjust
1178 // the instantiation location accordingly.
1179
1180 // If the location is from a macro instantiation, get the end of
1181 // the instantiation range.
1182 if (Loc.isMacroID())
1183 InstLoc = SM.getInstantiationRange(Loc).second;
1184
1185 // Measure the length token we're pointing at, so we can adjust
1186 // the physical location in the file to point at the last
1187 // character.
1188 // FIXME: This won't cope with trigraphs or escaped newlines
1189 // well. For that, we actually need a preprocessor, which isn't
1190 // currently available here. Eventually, we'll switch the pointer
1191 // data of CXSourceLocation/CXSourceRange to a translation unit
1192 // (CXXUnit), so that the preprocessor will be available here. At
1193 // that point, we can use Preprocessor::getLocForEndOfToken().
1194 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
Douglas Gregor5352ac02010-01-28 00:27:43 +00001195 *static_cast<LangOptions *>(location.ptr_data[1]));
Douglas Gregor1db19de2010-01-19 21:36:55 +00001196 if (Length > 0)
1197 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
1198 }
1199
1200 if (file)
1201 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1202 if (line)
1203 *line = SM.getInstantiationLineNumber(InstLoc);
1204 if (column)
1205 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001206 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001207 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001208}
1209
Douglas Gregor1db19de2010-01-19 21:36:55 +00001210CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001211 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1212 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001213 return Result;
1214}
1215
1216CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001217 cxloc::CXSourceLocationPtr Ptr;
1218 Ptr.setPointer(static_cast<SourceManager *>(range.ptr_data[0]));
Douglas Gregor1db19de2010-01-19 21:36:55 +00001219 Ptr.setInt(true);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001220 CXSourceLocation Result = { { Ptr.getOpaqueValue(), range.ptr_data[1] },
1221 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001222 return Result;
1223}
1224
Douglas Gregorb9790342010-01-22 21:44:22 +00001225} // end: extern "C"
1226
Douglas Gregor1db19de2010-01-19 21:36:55 +00001227//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001228// CXFile Operations.
1229//===----------------------------------------------------------------------===//
1230
1231extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001232const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001233 if (!SFile)
1234 return 0;
1235
Steve Naroff88145032009-10-27 14:35:18 +00001236 assert(SFile && "Passed null CXFile");
1237 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1238 return FEnt->getName();
1239}
1240
1241time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001242 if (!SFile)
1243 return 0;
1244
Steve Naroff88145032009-10-27 14:35:18 +00001245 assert(SFile && "Passed null CXFile");
1246 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1247 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001248}
Douglas Gregorb9790342010-01-22 21:44:22 +00001249
1250CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1251 if (!tu)
1252 return 0;
1253
1254 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1255
1256 FileManager &FMgr = CXXUnit->getFileManager();
1257 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1258 return const_cast<FileEntry *>(File);
1259}
1260
Ted Kremenekfb480492010-01-13 21:46:36 +00001261} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001262
Ted Kremenekfb480492010-01-13 21:46:36 +00001263//===----------------------------------------------------------------------===//
1264// CXCursor Operations.
1265//===----------------------------------------------------------------------===//
1266
Ted Kremenekfb480492010-01-13 21:46:36 +00001267static Decl *getDeclFromExpr(Stmt *E) {
1268 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1269 return RefExpr->getDecl();
1270 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1271 return ME->getMemberDecl();
1272 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1273 return RE->getDecl();
1274
1275 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1276 return getDeclFromExpr(CE->getCallee());
1277 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1278 return getDeclFromExpr(CE->getSubExpr());
1279 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1280 return OME->getMethodDecl();
1281
1282 return 0;
1283}
1284
1285extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001286
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001287unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001288 CXCursorVisitor visitor,
1289 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001290 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001291
1292 unsigned PCHLevel = Decl::MaxPCHLevel;
1293
1294 // Set the PCHLevel to filter out unwanted decls if requested.
1295 if (CXXUnit->getOnlyLocalDecls()) {
1296 PCHLevel = 0;
1297
1298 // If the main input was an AST, bump the level.
1299 if (CXXUnit->isMainFileAST())
1300 ++PCHLevel;
1301 }
1302
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001303 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001304 return CursorVis.VisitChildren(parent);
1305}
1306
Douglas Gregor78205d42010-01-20 21:45:58 +00001307static CXString getDeclSpelling(Decl *D) {
1308 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1309 if (!ND)
1310 return CIndexer::createCXString("");
1311
1312 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1313 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1314 true);
1315
1316 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1317 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1318 // and returns different names. NamedDecl returns the class name and
1319 // ObjCCategoryImplDecl returns the category name.
1320 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1321
1322 if (ND->getIdentifier())
1323 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1324
1325 return CIndexer::createCXString("");
1326}
1327
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001328CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +00001329 assert(getCursorDecl(C) && "CXCursor has null decl");
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001330 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001331 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001332
Steve Narofff334b4e2009-09-02 18:26:48 +00001333 if (clang_isReference(C.kind)) {
1334 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001335 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001336 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1337 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001338 }
1339 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001340 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1341 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001342 }
1343 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001344 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001345 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001346 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001347 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001348 case CXCursor_TypeRef: {
1349 TypeDecl *Type = getCursorTypeRef(C).first;
1350 assert(Type && "Missing type decl");
1351
1352 return CIndexer::createCXString(
1353 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1354 true);
1355 }
1356
Daniel Dunbaracca7252009-11-30 20:42:49 +00001357 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001358 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001359 }
1360 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001361
1362 if (clang_isExpression(C.kind)) {
1363 Decl *D = getDeclFromExpr(getCursorExpr(C));
1364 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001365 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001366 return CIndexer::createCXString("");
1367 }
1368
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001369 if (clang_isDeclaration(C.kind))
1370 return getDeclSpelling(getCursorDecl(C));
1371
1372 return CIndexer::createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001373}
1374
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001375const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001376 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001377 case CXCursor_FunctionDecl: return "FunctionDecl";
1378 case CXCursor_TypedefDecl: return "TypedefDecl";
1379 case CXCursor_EnumDecl: return "EnumDecl";
1380 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1381 case CXCursor_StructDecl: return "StructDecl";
1382 case CXCursor_UnionDecl: return "UnionDecl";
1383 case CXCursor_ClassDecl: return "ClassDecl";
1384 case CXCursor_FieldDecl: return "FieldDecl";
1385 case CXCursor_VarDecl: return "VarDecl";
1386 case CXCursor_ParmDecl: return "ParmDecl";
1387 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1388 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1389 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1390 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1391 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1392 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1393 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001394 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1395 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001396 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001397 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1398 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1399 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001400 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001401 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1402 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1403 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1404 case CXCursor_CallExpr: return "CallExpr";
1405 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1406 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001407 case CXCursor_InvalidFile: return "InvalidFile";
1408 case CXCursor_NoDeclFound: return "NoDeclFound";
1409 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001410 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001411 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001412
1413 llvm_unreachable("Unhandled CXCursorKind");
1414 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001415}
Steve Naroff89922f82009-08-31 00:59:03 +00001416
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001417enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1418 CXCursor parent,
1419 CXClientData client_data) {
1420 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1421 *BestCursor = cursor;
1422 return CXChildVisit_Recurse;
1423}
1424
Douglas Gregorb9790342010-01-22 21:44:22 +00001425CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1426 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001427 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001428
Douglas Gregorb9790342010-01-22 21:44:22 +00001429 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1430
Ted Kremeneka297de22010-01-25 22:34:44 +00001431 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001432 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1433 if (SLoc.isValid()) {
1434 SourceRange RegionOfInterest(SLoc,
1435 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1436
1437 // FIXME: Would be great to have a "hint" cursor, then walk from that
1438 // hint cursor upward until we find a cursor whose source range encloses
1439 // the region of interest, rather than starting from the translation unit.
1440 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1441 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1442 Decl::MaxPCHLevel, RegionOfInterest);
1443 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001444 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001445 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001446}
1447
Ted Kremenek73885552009-11-17 19:28:59 +00001448CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001449 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001450}
1451
1452unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001453 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001454}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001455
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001456unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001457 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1458}
1459
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001460unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001461 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1462}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001463
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001464unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001465 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1466}
1467
Douglas Gregor97b98722010-01-19 23:20:36 +00001468unsigned clang_isExpression(enum CXCursorKind K) {
1469 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1470}
1471
1472unsigned clang_isStatement(enum CXCursorKind K) {
1473 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1474}
1475
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001476unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1477 return K == CXCursor_TranslationUnit;
1478}
1479
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001480CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001481 return C.kind;
1482}
1483
Douglas Gregor97b98722010-01-19 23:20:36 +00001484static SourceLocation getLocationFromExpr(Expr *E) {
1485 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1486 return /*FIXME:*/Msg->getLeftLoc();
1487 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1488 return DRE->getLocation();
1489 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1490 return Member->getMemberLoc();
1491 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1492 return Ivar->getLocation();
1493 return E->getLocStart();
1494}
1495
Douglas Gregor98258af2010-01-18 22:46:11 +00001496CXSourceLocation clang_getCursorLocation(CXCursor C) {
1497 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001498 switch (C.kind) {
1499 case CXCursor_ObjCSuperClassRef: {
1500 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1501 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001502 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001503 }
1504
1505 case CXCursor_ObjCProtocolRef: {
1506 std::pair<ObjCProtocolDecl *, SourceLocation> P
1507 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001508 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001509 }
1510
1511 case CXCursor_ObjCClassRef: {
1512 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1513 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001514 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001515 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001516
1517 case CXCursor_TypeRef: {
1518 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001519 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001520 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001521
Douglas Gregorf46034a2010-01-18 23:41:10 +00001522 default:
1523 // FIXME: Need a way to enumerate all non-reference cases.
1524 llvm_unreachable("Missed a reference kind");
1525 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001526 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001527
1528 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001529 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001530 getLocationFromExpr(getCursorExpr(C)));
1531
Douglas Gregor5352ac02010-01-28 00:27:43 +00001532 if (!getCursorDecl(C))
1533 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001534
Douglas Gregorf46034a2010-01-18 23:41:10 +00001535 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001536 SourceLocation Loc = D->getLocation();
1537 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1538 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001539 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001540}
Douglas Gregora7bde202010-01-19 00:34:46 +00001541
1542CXSourceRange clang_getCursorExtent(CXCursor C) {
1543 if (clang_isReference(C.kind)) {
1544 switch (C.kind) {
1545 case CXCursor_ObjCSuperClassRef: {
1546 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1547 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001548 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001549 }
1550
1551 case CXCursor_ObjCProtocolRef: {
1552 std::pair<ObjCProtocolDecl *, SourceLocation> P
1553 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001554 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001555 }
1556
1557 case CXCursor_ObjCClassRef: {
1558 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1559 = getCursorObjCClassRef(C);
1560
Ted Kremeneka297de22010-01-25 22:34:44 +00001561 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001562 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001563
1564 case CXCursor_TypeRef: {
1565 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001566 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001567 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001568
Douglas Gregora7bde202010-01-19 00:34:46 +00001569 default:
1570 // FIXME: Need a way to enumerate all non-reference cases.
1571 llvm_unreachable("Missed a reference kind");
1572 }
1573 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001574
1575 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001576 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001577 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001578
1579 if (clang_isStatement(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001580 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001581 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001582
Douglas Gregor5352ac02010-01-28 00:27:43 +00001583 if (!getCursorDecl(C))
1584 return clang_getNullRange();
Douglas Gregora7bde202010-01-19 00:34:46 +00001585
1586 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001587 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001588}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001589
1590CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001591 if (clang_isInvalid(C.kind))
1592 return clang_getNullCursor();
1593
1594 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001595 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001596 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001597
Douglas Gregor97b98722010-01-19 23:20:36 +00001598 if (clang_isExpression(C.kind)) {
1599 Decl *D = getDeclFromExpr(getCursorExpr(C));
1600 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001601 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001602 return clang_getNullCursor();
1603 }
1604
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001605 if (!clang_isReference(C.kind))
1606 return clang_getNullCursor();
1607
1608 switch (C.kind) {
1609 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001610 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001611
1612 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001613 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001614
1615 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001616 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001617
1618 case CXCursor_TypeRef:
1619 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001620
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001621 default:
1622 // We would prefer to enumerate all non-reference cursor kinds here.
1623 llvm_unreachable("Unhandled reference cursor kind");
1624 break;
1625 }
1626 }
1627
1628 return clang_getNullCursor();
1629}
1630
Douglas Gregorb6998662010-01-19 19:34:47 +00001631CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001632 if (clang_isInvalid(C.kind))
1633 return clang_getNullCursor();
1634
1635 ASTUnit *CXXUnit = getCursorASTUnit(C);
1636
Douglas Gregorb6998662010-01-19 19:34:47 +00001637 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001638 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001639 C = clang_getCursorReferenced(C);
1640 WasReference = true;
1641 }
1642
1643 if (!clang_isDeclaration(C.kind))
1644 return clang_getNullCursor();
1645
1646 Decl *D = getCursorDecl(C);
1647 if (!D)
1648 return clang_getNullCursor();
1649
1650 switch (D->getKind()) {
1651 // Declaration kinds that don't really separate the notions of
1652 // declaration and definition.
1653 case Decl::Namespace:
1654 case Decl::Typedef:
1655 case Decl::TemplateTypeParm:
1656 case Decl::EnumConstant:
1657 case Decl::Field:
1658 case Decl::ObjCIvar:
1659 case Decl::ObjCAtDefsField:
1660 case Decl::ImplicitParam:
1661 case Decl::ParmVar:
1662 case Decl::NonTypeTemplateParm:
1663 case Decl::TemplateTemplateParm:
1664 case Decl::ObjCCategoryImpl:
1665 case Decl::ObjCImplementation:
1666 case Decl::LinkageSpec:
1667 case Decl::ObjCPropertyImpl:
1668 case Decl::FileScopeAsm:
1669 case Decl::StaticAssert:
1670 case Decl::Block:
1671 return C;
1672
1673 // Declaration kinds that don't make any sense here, but are
1674 // nonetheless harmless.
1675 case Decl::TranslationUnit:
1676 case Decl::Template:
1677 case Decl::ObjCContainer:
1678 break;
1679
1680 // Declaration kinds for which the definition is not resolvable.
1681 case Decl::UnresolvedUsingTypename:
1682 case Decl::UnresolvedUsingValue:
1683 break;
1684
1685 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001686 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1687 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001688
1689 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001690 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001691
1692 case Decl::Enum:
1693 case Decl::Record:
1694 case Decl::CXXRecord:
1695 case Decl::ClassTemplateSpecialization:
1696 case Decl::ClassTemplatePartialSpecialization:
1697 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001698 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001699 return clang_getNullCursor();
1700
1701 case Decl::Function:
1702 case Decl::CXXMethod:
1703 case Decl::CXXConstructor:
1704 case Decl::CXXDestructor:
1705 case Decl::CXXConversion: {
1706 const FunctionDecl *Def = 0;
1707 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001708 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001709 return clang_getNullCursor();
1710 }
1711
1712 case Decl::Var: {
1713 VarDecl *Var = cast<VarDecl>(D);
1714
1715 // Variables with initializers have definitions.
1716 const VarDecl *Def = 0;
1717 if (Var->getDefinition(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001718 return MakeCXCursor(const_cast<VarDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001719
1720 // extern and private_extern variables are not definitions.
1721 if (Var->hasExternalStorage())
1722 return clang_getNullCursor();
1723
1724 // In-line static data members do not have definitions.
1725 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1726 return clang_getNullCursor();
1727
1728 // All other variables are themselves definitions.
1729 return C;
1730 }
1731
1732 case Decl::FunctionTemplate: {
1733 const FunctionDecl *Def = 0;
1734 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001735 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001736 return clang_getNullCursor();
1737 }
1738
1739 case Decl::ClassTemplate: {
1740 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1741 ->getDefinition(D->getASTContext()))
1742 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001743 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1744 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001745 return clang_getNullCursor();
1746 }
1747
1748 case Decl::Using: {
1749 UsingDecl *Using = cast<UsingDecl>(D);
1750 CXCursor Def = clang_getNullCursor();
1751 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1752 SEnd = Using->shadow_end();
1753 S != SEnd; ++S) {
1754 if (Def != clang_getNullCursor()) {
1755 // FIXME: We have no way to return multiple results.
1756 return clang_getNullCursor();
1757 }
1758
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001759 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1760 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001761 }
1762
1763 return Def;
1764 }
1765
1766 case Decl::UsingShadow:
1767 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001768 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1769 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001770
1771 case Decl::ObjCMethod: {
1772 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1773 if (Method->isThisDeclarationADefinition())
1774 return C;
1775
1776 // Dig out the method definition in the associated
1777 // @implementation, if we have it.
1778 // FIXME: The ASTs should make finding the definition easier.
1779 if (ObjCInterfaceDecl *Class
1780 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1781 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1782 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1783 Method->isInstanceMethod()))
1784 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001785 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001786
1787 return clang_getNullCursor();
1788 }
1789
1790 case Decl::ObjCCategory:
1791 if (ObjCCategoryImplDecl *Impl
1792 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001793 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001794 return clang_getNullCursor();
1795
1796 case Decl::ObjCProtocol:
1797 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1798 return C;
1799 return clang_getNullCursor();
1800
1801 case Decl::ObjCInterface:
1802 // There are two notions of a "definition" for an Objective-C
1803 // class: the interface and its implementation. When we resolved a
1804 // reference to an Objective-C class, produce the @interface as
1805 // the definition; when we were provided with the interface,
1806 // produce the @implementation as the definition.
1807 if (WasReference) {
1808 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1809 return C;
1810 } else if (ObjCImplementationDecl *Impl
1811 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001812 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001813 return clang_getNullCursor();
1814
1815 case Decl::ObjCProperty:
1816 // FIXME: We don't really know where to find the
1817 // ObjCPropertyImplDecls that implement this property.
1818 return clang_getNullCursor();
1819
1820 case Decl::ObjCCompatibleAlias:
1821 if (ObjCInterfaceDecl *Class
1822 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1823 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001824 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001825
1826 return clang_getNullCursor();
1827
1828 case Decl::ObjCForwardProtocol: {
1829 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1830 if (Forward->protocol_size() == 1)
1831 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001832 MakeCXCursor(*Forward->protocol_begin(),
1833 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001834
1835 // FIXME: Cannot return multiple definitions.
1836 return clang_getNullCursor();
1837 }
1838
1839 case Decl::ObjCClass: {
1840 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1841 if (Class->size() == 1) {
1842 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1843 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001844 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001845 return clang_getNullCursor();
1846 }
1847
1848 // FIXME: Cannot return multiple definitions.
1849 return clang_getNullCursor();
1850 }
1851
1852 case Decl::Friend:
1853 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001854 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001855 return clang_getNullCursor();
1856
1857 case Decl::FriendTemplate:
1858 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001859 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001860 return clang_getNullCursor();
1861 }
1862
1863 return clang_getNullCursor();
1864}
1865
1866unsigned clang_isCursorDefinition(CXCursor C) {
1867 if (!clang_isDeclaration(C.kind))
1868 return 0;
1869
1870 return clang_getCursorDefinition(C) == C;
1871}
1872
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001873void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001874 const char **startBuf,
1875 const char **endBuf,
1876 unsigned *startLine,
1877 unsigned *startColumn,
1878 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001879 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001880 assert(getCursorDecl(C) && "CXCursor has null decl");
1881 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001882 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1883 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001884
Steve Naroff4ade6d62009-09-23 17:52:52 +00001885 SourceManager &SM = FD->getASTContext().getSourceManager();
1886 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1887 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1888 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1889 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1890 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1891 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1892}
Ted Kremenekfb480492010-01-13 21:46:36 +00001893
1894} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001895
Ted Kremenekfb480492010-01-13 21:46:36 +00001896//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001897// Token-based Operations.
1898//===----------------------------------------------------------------------===//
1899
1900/* CXToken layout:
1901 * int_data[0]: a CXTokenKind
1902 * int_data[1]: starting token location
1903 * int_data[2]: token length
1904 * int_data[3]: reserved
1905 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
1906 * otherwise unused.
1907 */
1908extern "C" {
1909
1910CXTokenKind clang_getTokenKind(CXToken CXTok) {
1911 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1912}
1913
1914CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1915 switch (clang_getTokenKind(CXTok)) {
1916 case CXToken_Identifier:
1917 case CXToken_Keyword:
1918 // We know we have an IdentifierInfo*, so use that.
1919 return CIndexer::createCXString(
1920 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
1921
1922 case CXToken_Literal: {
1923 // We have stashed the starting pointer in the ptr_data field. Use it.
1924 const char *Text = static_cast<const char *>(CXTok.ptr_data);
1925 return CIndexer::createCXString(llvm::StringRef(Text, CXTok.int_data[2]),
1926 true);
1927 }
1928
1929 case CXToken_Punctuation:
1930 case CXToken_Comment:
1931 break;
1932 }
1933
1934 // We have to find the starting buffer pointer the hard way, by
1935 // deconstructing the source location.
1936 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1937 if (!CXXUnit)
1938 return CIndexer::createCXString("");
1939
1940 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1941 std::pair<FileID, unsigned> LocInfo
1942 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1943 std::pair<const char *,const char *> Buffer
1944 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1945
1946 return CIndexer::createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1947 CXTok.int_data[2]),
1948 true);
1949}
1950
1951CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1952 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1953 if (!CXXUnit)
1954 return clang_getNullLocation();
1955
1956 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1957 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1958}
1959
1960CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1961 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001962 if (!CXXUnit)
1963 return clang_getNullRange();
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001964
1965 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
1966 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1967}
1968
1969void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1970 CXToken **Tokens, unsigned *NumTokens) {
1971 if (Tokens)
1972 *Tokens = 0;
1973 if (NumTokens)
1974 *NumTokens = 0;
1975
1976 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1977 if (!CXXUnit || !Tokens || !NumTokens)
1978 return;
1979
1980 SourceRange R = cxloc::translateSourceRange(Range);
1981 if (R.isInvalid())
1982 return;
1983
1984 SourceManager &SourceMgr = CXXUnit->getSourceManager();
1985 std::pair<FileID, unsigned> BeginLocInfo
1986 = SourceMgr.getDecomposedLoc(R.getBegin());
1987 std::pair<FileID, unsigned> EndLocInfo
1988 = SourceMgr.getDecomposedLoc(R.getEnd());
1989
1990 // Cannot tokenize across files.
1991 if (BeginLocInfo.first != EndLocInfo.first)
1992 return;
1993
1994 // Create a lexer
1995 std::pair<const char *,const char *> Buffer
1996 = SourceMgr.getBufferData(BeginLocInfo.first);
1997 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
1998 CXXUnit->getASTContext().getLangOptions(),
1999 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
2000 Lex.SetCommentRetentionState(true);
2001
2002 // Lex tokens until we hit the end of the range.
2003 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
2004 llvm::SmallVector<CXToken, 32> CXTokens;
2005 Token Tok;
2006 do {
2007 // Lex the next token
2008 Lex.LexFromRawLexer(Tok);
2009 if (Tok.is(tok::eof))
2010 break;
2011
2012 // Initialize the CXToken.
2013 CXToken CXTok;
2014
2015 // - Common fields
2016 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2017 CXTok.int_data[2] = Tok.getLength();
2018 CXTok.int_data[3] = 0;
2019
2020 // - Kind-specific fields
2021 if (Tok.isLiteral()) {
2022 CXTok.int_data[0] = CXToken_Literal;
2023 CXTok.ptr_data = (void *)Tok.getLiteralData();
2024 } else if (Tok.is(tok::identifier)) {
2025 // Lookup the identifier to determine whether we have a
2026 std::pair<FileID, unsigned> LocInfo
2027 = SourceMgr.getDecomposedLoc(Tok.getLocation());
2028 const char *StartPos
2029 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
2030 LocInfo.second;
2031 IdentifierInfo *II
2032 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2033 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2034 CXToken_Identifier
2035 : CXToken_Keyword;
2036 CXTok.ptr_data = II;
2037 } else if (Tok.is(tok::comment)) {
2038 CXTok.int_data[0] = CXToken_Comment;
2039 CXTok.ptr_data = 0;
2040 } else {
2041 CXTok.int_data[0] = CXToken_Punctuation;
2042 CXTok.ptr_data = 0;
2043 }
2044 CXTokens.push_back(CXTok);
2045 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2046
2047 if (CXTokens.empty())
2048 return;
2049
2050 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2051 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2052 *NumTokens = CXTokens.size();
2053}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002054
2055typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2056
2057enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2058 CXCursor parent,
2059 CXClientData client_data) {
2060 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2061
2062 // We only annotate the locations of declarations, simple
2063 // references, and expressions which directly reference something.
2064 CXCursorKind Kind = clang_getCursorKind(cursor);
2065 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2066 // Okay: We can annotate the location of this declaration with the
2067 // declaration or reference
2068 } else if (clang_isExpression(cursor.kind)) {
2069 if (Kind != CXCursor_DeclRefExpr &&
2070 Kind != CXCursor_MemberRefExpr &&
2071 Kind != CXCursor_ObjCMessageExpr)
2072 return CXChildVisit_Recurse;
2073
2074 CXCursor Referenced = clang_getCursorReferenced(cursor);
2075 if (Referenced == cursor || Referenced == clang_getNullCursor())
2076 return CXChildVisit_Recurse;
2077
2078 // Okay: we can annotate the location of this expression
2079 } else {
2080 // Nothing to annotate
2081 return CXChildVisit_Recurse;
2082 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002083
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002084 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2085 (*Data)[Loc.int_data] = cursor;
2086 return CXChildVisit_Recurse;
2087}
2088
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002089void clang_annotateTokens(CXTranslationUnit TU,
2090 CXToken *Tokens, unsigned NumTokens,
2091 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002092 if (NumTokens == 0)
2093 return;
2094
2095 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002096 for (unsigned I = 0; I != NumTokens; ++I)
2097 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002098
2099 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2100 if (!CXXUnit || !Tokens)
2101 return;
2102
2103 // Annotate all of the source locations in the region of interest that map
2104 SourceRange RegionOfInterest;
2105 RegionOfInterest.setBegin(
2106 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2107 SourceLocation End
2108 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2109 Tokens[NumTokens - 1]));
2110 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End,
2111 1));
2112 // FIXME: Would be great to have a "hint" cursor, then walk from that
2113 // hint cursor upward until we find a cursor whose source range encloses
2114 // the region of interest, rather than starting from the translation unit.
2115 AnnotateTokensData Annotated;
2116 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2117 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2118 Decl::MaxPCHLevel, RegionOfInterest);
2119 AnnotateVis.VisitChildren(Parent);
2120
2121 for (unsigned I = 0; I != NumTokens; ++I) {
2122 // Determine whether we saw a cursor at this token's location.
2123 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2124 if (Pos == Annotated.end())
2125 continue;
2126
2127 Cursors[I] = Pos->second;
2128 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002129}
2130
2131void clang_disposeTokens(CXTranslationUnit TU,
2132 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002133 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002134}
2135
2136} // end: extern "C"
2137
2138//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002139// CXString Operations.
2140//===----------------------------------------------------------------------===//
2141
2142extern "C" {
2143const char *clang_getCString(CXString string) {
2144 return string.Spelling;
2145}
2146
2147void clang_disposeString(CXString string) {
2148 if (string.MustFreeString && string.Spelling)
2149 free((void*)string.Spelling);
2150}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002151
Ted Kremenekfb480492010-01-13 21:46:36 +00002152} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002153
2154//===----------------------------------------------------------------------===//
2155// Misc. utility functions.
2156//===----------------------------------------------------------------------===//
2157
2158extern "C" {
2159
2160const char *clang_getClangVersion() {
Ted Kremeneka18f1b82010-01-23 02:11:34 +00002161 return getClangFullVersion();
Ted Kremenek04bb7162010-01-22 22:44:15 +00002162}
2163
2164} // end: extern "C"
2165