blob: ee73946dc109b8d2d38d9ee471bd23b8f92664ef [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000017#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000018#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000019
Ted Kremenek04bb7162010-01-22 22:44:15 +000020#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000021
Steve Naroff50398192009-08-28 15:28:48 +000022#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000024#include "clang/AST/TypeLocVisitor.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000026#include "clang/Lex/Lexer.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000027#include "clang/Lex/Preprocessor.h"
Douglas Gregor02465752009-10-16 21:24:31 +000028#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000029#include "llvm/System/Program.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000030
Ted Kremenekdb3d0da2010-01-05 20:55:39 +000031// Needed to define L_TMPNAM on some systems.
32#include <cstdio>
33
Steve Naroff50398192009-08-28 15:28:48 +000034using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000035using namespace clang::cxcursor;
Steve Naroff50398192009-08-28 15:28:48 +000036using namespace idx;
37
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000038//===----------------------------------------------------------------------===//
39// Crash Reporting.
40//===----------------------------------------------------------------------===//
41
42#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000043#ifndef NDEBUG
44#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000045#include "clang/Analysis/Support/SaveAndRestore.h"
46// Integrate with crash reporter.
47extern "C" const char *__crashreporter_info__;
Ted Kremenek29b72842010-01-07 22:49:05 +000048#define NUM_CRASH_STRINGS 16
49static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000050static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000051static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
52static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
53
54static unsigned SetCrashTracerInfo(const char *str,
55 llvm::SmallString<1024> &AggStr) {
56
Ted Kremenek254ba7c2010-01-07 23:13:53 +000057 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000058 while (crashtracer_strings[slot]) {
59 if (++slot == NUM_CRASH_STRINGS)
60 slot = 0;
61 }
62 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000063 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000064
65 // We need to create an aggregate string because multiple threads
66 // may be in this method at one time. The crash reporter string
67 // will attempt to overapproximate the set of in-flight invocations
68 // of this function. Race conditions can still cause this goal
69 // to not be achieved.
70 {
71 llvm::raw_svector_ostream Out(AggStr);
72 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
73 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
74 }
75 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
76 return slot;
77}
78
79static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000080 unsigned max_slot = 0;
81 unsigned max_value = 0;
82
83 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
84
85 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
86 if (agg_crashtracer_strings[i] &&
87 crashtracer_counter_id[i] > max_value) {
88 max_slot = i;
89 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000090 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000091
92 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000093}
94
95namespace {
96class ArgsCrashTracerInfo {
97 llvm::SmallString<1024> CrashString;
98 llvm::SmallString<1024> AggregateString;
99 unsigned crashtracerSlot;
100public:
101 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
102 : crashtracerSlot(0)
103 {
104 {
105 llvm::raw_svector_ostream Out(CrashString);
106 Out << "ClangCIndex [createTranslationUnitFromSourceFile]: clang";
107 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
108 E=Args.end(); I!=E; ++I)
109 Out << ' ' << *I;
110 }
111 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
112 AggregateString);
113 }
114
115 ~ArgsCrashTracerInfo() {
116 ResetCrashTracerInfo(crashtracerSlot);
117 }
118};
119}
120#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121#endif
122
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000123/// \brief The result of comparing two source ranges.
124enum RangeComparisonResult {
125 /// \brief Either the ranges overlap or one of the ranges is invalid.
126 RangeOverlap,
127
128 /// \brief The first range ends before the second range starts.
129 RangeBefore,
130
131 /// \brief The first range starts after the second range ends.
132 RangeAfter
133};
134
135/// \brief Compare two source ranges to determine their relative position in
136/// the translation unit.
137static RangeComparisonResult RangeCompare(SourceManager &SM,
138 SourceRange R1,
139 SourceRange R2) {
140 assert(R1.isValid() && "First range is invalid?");
141 assert(R2.isValid() && "Second range is invalid?");
142 if (SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
143 return RangeBefore;
144 if (SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
145 return RangeAfter;
146 return RangeOverlap;
147}
148
Douglas Gregor1db19de2010-01-19 21:36:55 +0000149
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000150//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000152//===----------------------------------------------------------------------===//
153
Steve Naroff89922f82009-08-31 00:59:03 +0000154namespace {
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000155
Douglas Gregorb1373d02010-01-20 20:59:29 +0000156// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000157class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000158 public TypeLocVisitor<CursorVisitor, bool>,
159 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000160{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000161 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000162 ASTUnit *TU;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000163
164 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000165 CXCursor Parent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000166
167 /// \brief The declaration that serves at the parent of any statement or
168 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000169 Decl *StmtParent;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000170
171 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000172 CXCursorVisitor Visitor;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000173
174 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000175 CXClientData ClientData;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000176
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000177 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
178 // to the visitor. Declarations with a PCH level greater than this value will
179 // be suppressed.
180 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181
182 /// \brief When valid, a source range to which the cursor should restrict
183 /// its search.
184 SourceRange RegionOfInterest;
185
Douglas Gregorb1373d02010-01-20 20:59:29 +0000186 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000187 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000188 using StmtVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000189
190 /// \brief Determine whether this particular source range comes before, comes
191 /// after, or overlaps the region of interest.
192 ///
193 /// \param R a source range retrieved from the abstract syntax tree.
194 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
195
196 /// \brief Determine whether this particular source range comes before, comes
197 /// after, or overlaps the region of interest.
198 ///
199 /// \param CXR a source range retrieved from a cursor.
200 RangeComparisonResult CompareRegionOfInterest(CXSourceRange CXR);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000201
Steve Naroff89922f82009-08-31 00:59:03 +0000202public:
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000203 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000204 unsigned MaxPCHLevel,
205 SourceRange RegionOfInterest = SourceRange())
206 : TU(TU), Visitor(Visitor), ClientData(ClientData),
207 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000208 {
209 Parent.kind = CXCursor_NoDeclFound;
210 Parent.data[0] = 0;
211 Parent.data[1] = 0;
212 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000213 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000214 }
215
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000216 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000217 bool VisitChildren(CXCursor Parent);
218
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000219 // Declaration visitors
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220 bool VisitDeclContext(DeclContext *DC);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000221 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000222 bool VisitTypedefDecl(TypedefDecl *D);
223 bool VisitTagDecl(TagDecl *D);
224 bool VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000225 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000226 bool VisitFunctionDecl(FunctionDecl *ND);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000227 bool VisitFieldDecl(FieldDecl *D);
228 bool VisitVarDecl(VarDecl *);
229 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
Douglas Gregora59e3902010-01-21 23:27:09 +0000230 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000231 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000232 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000233 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
234 bool VisitObjCImplDecl(ObjCImplDecl *D);
235 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
236 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
237 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
238 // etc.
239 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
240 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
241 bool VisitObjCClassDecl(ObjCClassDecl *D);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000242
243 // Type visitors
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000244 // FIXME: QualifiedTypeLoc doesn't provide any location information
245 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000246 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000247 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
248 bool VisitTagTypeLoc(TagTypeLoc TL);
249 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
250 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
251 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
252 bool VisitPointerTypeLoc(PointerTypeLoc TL);
253 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
254 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
255 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
256 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
257 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
258 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000259 // FIXME: Implement for TemplateSpecializationTypeLoc
260 // FIXME: Implement visitors here when the unimplemented TypeLocs get
261 // implemented
262 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
263 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Douglas Gregora59e3902010-01-21 23:27:09 +0000264
265 // Statement visitors
266 bool VisitStmt(Stmt *S);
267 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000268 // FIXME: LabelStmt label?
269 bool VisitIfStmt(IfStmt *S);
270 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000271 bool VisitWhileStmt(WhileStmt *S);
272 bool VisitForStmt(ForStmt *S);
Douglas Gregor336fd812010-01-23 00:40:08 +0000273
274 // Expression visitors
275 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
276 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
277 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000278};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000279
Ted Kremenekab188932010-01-05 19:32:54 +0000280} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000281
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000282RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
283 assert(RegionOfInterest.isValid() && "RangeCompare called with invalid range");
284 if (R.isInvalid())
285 return RangeOverlap;
286
287 // Move the end of the input range to the end of the last token in that
288 // range.
289 R.setEnd(TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1));
290 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
291}
292
293RangeComparisonResult CursorVisitor::CompareRegionOfInterest(CXSourceRange CXR) {
Ted Kremeneka297de22010-01-25 22:34:44 +0000294 return CompareRegionOfInterest(cxloc::translateSourceRange(CXR));
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000295}
296
Douglas Gregorb1373d02010-01-20 20:59:29 +0000297/// \brief Visit the given cursor and, if requested by the visitor,
298/// its children.
299///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000300/// \param Cursor the cursor to visit.
301///
302/// \param CheckRegionOfInterest if true, then the caller already checked that
303/// this cursor is within the region of interest.
304///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000305/// \returns true if the visitation should be aborted, false if it
306/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000307bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000308 if (clang_isInvalid(Cursor.kind))
309 return false;
310
311 if (clang_isDeclaration(Cursor.kind)) {
312 Decl *D = getCursorDecl(Cursor);
313 assert(D && "Invalid declaration cursor");
314 if (D->getPCHLevel() > MaxPCHLevel)
315 return false;
316
317 if (D->isImplicit())
318 return false;
319 }
320
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000321 // If we have a range of interest, and this cursor doesn't intersect with it,
322 // we're done.
323 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
324 CXSourceRange Range = clang_getCursorExtent(Cursor);
Ted Kremeneka297de22010-01-25 22:34:44 +0000325 if (cxloc::translateSourceRange(Range).isInvalid() ||
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000326 CompareRegionOfInterest(Range))
327 return false;
328 }
329
Douglas Gregorb1373d02010-01-20 20:59:29 +0000330 switch (Visitor(Cursor, Parent, ClientData)) {
331 case CXChildVisit_Break:
332 return true;
333
334 case CXChildVisit_Continue:
335 return false;
336
337 case CXChildVisit_Recurse:
338 return VisitChildren(Cursor);
339 }
340
Douglas Gregorfd643772010-01-25 16:45:46 +0000341 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000342}
343
344/// \brief Visit the children of the given cursor.
345///
346/// \returns true if the visitation should be aborted, false if it
347/// should continue.
348bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000349 if (clang_isReference(Cursor.kind)) {
350 // By definition, references have no children.
351 return false;
352 }
353
Douglas Gregorb1373d02010-01-20 20:59:29 +0000354 // Set the Parent field to Cursor, then back to its old value once we're
355 // done.
356 class SetParentRAII {
357 CXCursor &Parent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000358 Decl *&StmtParent;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000359 CXCursor OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000360
Douglas Gregorb1373d02010-01-20 20:59:29 +0000361 public:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000362 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
363 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000364 {
365 Parent = NewParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000366 if (clang_isDeclaration(Parent.kind))
367 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000368 }
369
370 ~SetParentRAII() {
371 Parent = OldParent;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000372 if (clang_isDeclaration(Parent.kind))
373 StmtParent = getCursorDecl(Parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000374 }
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000375 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000376
377 if (clang_isDeclaration(Cursor.kind)) {
378 Decl *D = getCursorDecl(Cursor);
379 assert(D && "Invalid declaration cursor");
380 return Visit(D);
381 }
382
Douglas Gregora59e3902010-01-21 23:27:09 +0000383 if (clang_isStatement(Cursor.kind))
384 return Visit(getCursorStmt(Cursor));
385 if (clang_isExpression(Cursor.kind))
386 return Visit(getCursorExpr(Cursor));
387
Douglas Gregorb1373d02010-01-20 20:59:29 +0000388 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000389 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000390 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
391 RegionOfInterest.isInvalid()) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000392 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
393 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
394 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000395 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000396 return true;
397 }
398 } else {
399 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000401 }
402
403 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000404 }
Douglas Gregora59e3902010-01-21 23:27:09 +0000405
Douglas Gregorb1373d02010-01-20 20:59:29 +0000406 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000407 return false;
408}
409
Douglas Gregorb1373d02010-01-20 20:59:29 +0000410bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000411 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000412 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000413 if (RegionOfInterest.isValid()) {
414 SourceRange R = (*I)->getSourceRange();
415 if (R.isInvalid())
416 continue;
417
418 switch (CompareRegionOfInterest(R)) {
419 case RangeBefore:
420 // This declaration comes before the region of interest; skip it.
421 continue;
422
423 case RangeAfter:
424 // This declaration comes after the region of interest; we're done.
425 return false;
426
427 case RangeOverlap:
428 // This declaration overlaps the region of interest; visit it.
429 break;
430 }
431 }
432
433 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000434 return true;
435 }
436
437 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000438}
439
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000440bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
441 llvm_unreachable("Translation units are visited directly by Visit()");
442 return false;
443}
444
445bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
446 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
447 return Visit(TSInfo->getTypeLoc());
448
449 return false;
450}
451
452bool CursorVisitor::VisitTagDecl(TagDecl *D) {
453 return VisitDeclContext(D);
454}
455
456bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
457 if (Expr *Init = D->getInitExpr())
458 return Visit(MakeCXCursor(Init, StmtParent, TU));
459 return false;
460}
461
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000462bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
463 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
464 if (Visit(TSInfo->getTypeLoc()))
465 return true;
466
467 return false;
468}
469
Douglas Gregorb1373d02010-01-20 20:59:29 +0000470bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000471 if (VisitDeclaratorDecl(ND))
472 return true;
473
Douglas Gregora59e3902010-01-21 23:27:09 +0000474 if (ND->isThisDeclarationADefinition() &&
475 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
476 return true;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000477
478 return false;
479}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000480
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000481bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
482 if (VisitDeclaratorDecl(D))
483 return true;
484
485 if (Expr *BitWidth = D->getBitWidth())
486 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
487
488 return false;
489}
490
491bool CursorVisitor::VisitVarDecl(VarDecl *D) {
492 if (VisitDeclaratorDecl(D))
493 return true;
494
495 if (Expr *Init = D->getInit())
496 return Visit(MakeCXCursor(Init, StmtParent, TU));
497
498 return false;
499}
500
501bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
502 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
503 // At the moment, we don't have information about locations in the return
504 // type.
505 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
506 PEnd = ND->param_end();
507 P != PEnd; ++P) {
508 if (Visit(MakeCXCursor(*P, TU)))
509 return true;
510 }
511
512 if (ND->isThisDeclarationADefinition() &&
513 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
514 return true;
515
516 return false;
517}
518
Douglas Gregora59e3902010-01-21 23:27:09 +0000519bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
520 return VisitDeclContext(D);
521}
522
Douglas Gregorb1373d02010-01-20 20:59:29 +0000523bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000524 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
525 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000526 return true;
527
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000528 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
529 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
530 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000531 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000532 return true;
533
Douglas Gregora59e3902010-01-21 23:27:09 +0000534 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000535}
536
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000537bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
538 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
539 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
540 E = PID->protocol_end(); I != E; ++I, ++PL)
541 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
542 return true;
543
544 return VisitObjCContainerDecl(PID);
545}
546
Douglas Gregorb1373d02010-01-20 20:59:29 +0000547bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000548 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000549 if (D->getSuperClass() &&
550 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000551 D->getSuperClassLoc(),
552 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000553 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000554
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000555 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
556 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
557 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000558 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 return true;
560
Douglas Gregora59e3902010-01-21 23:27:09 +0000561 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000562}
563
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000564bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
565 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000566}
567
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000568bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
569 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
570 D->getLocation(), TU)))
571 return true;
572
573 return VisitObjCImplDecl(D);
574}
575
576bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
577#if 0
578 // Issue callbacks for super class.
579 // FIXME: No source location information!
580 if (D->getSuperClass() &&
581 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
582 D->getSuperClassLoc(),
583 TU)))
584 return true;
585#endif
586
587 return VisitObjCImplDecl(D);
588}
589
590bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
591 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
592 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
593 E = D->protocol_end();
594 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000595 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000596 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000597
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000598 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000599}
600
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000601bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
602 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
603 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
604 return true;
605
606 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000607}
608
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000609bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
610 ASTContext &Context = TU->getASTContext();
611
612 // Some builtin types (such as Objective-C's "id", "sel", and
613 // "Class") have associated declarations. Create cursors for those.
614 QualType VisitType;
615 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
616 case BuiltinType::Void:
617 case BuiltinType::Bool:
618 case BuiltinType::Char_U:
619 case BuiltinType::UChar:
620 case BuiltinType::Char16:
621 case BuiltinType::Char32:
622 case BuiltinType::UShort:
623 case BuiltinType::UInt:
624 case BuiltinType::ULong:
625 case BuiltinType::ULongLong:
626 case BuiltinType::UInt128:
627 case BuiltinType::Char_S:
628 case BuiltinType::SChar:
629 case BuiltinType::WChar:
630 case BuiltinType::Short:
631 case BuiltinType::Int:
632 case BuiltinType::Long:
633 case BuiltinType::LongLong:
634 case BuiltinType::Int128:
635 case BuiltinType::Float:
636 case BuiltinType::Double:
637 case BuiltinType::LongDouble:
638 case BuiltinType::NullPtr:
639 case BuiltinType::Overload:
640 case BuiltinType::Dependent:
641 break;
642
643 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
644 break;
645
646 case BuiltinType::ObjCId:
647 VisitType = Context.getObjCIdType();
648 break;
649
650 case BuiltinType::ObjCClass:
651 VisitType = Context.getObjCClassType();
652 break;
653
654 case BuiltinType::ObjCSel:
655 VisitType = Context.getObjCSelType();
656 break;
657 }
658
659 if (!VisitType.isNull()) {
660 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
661 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
662 TU));
663 }
664
665 return false;
666}
667
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000668bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
669 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
670}
671
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000672bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
673 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
674}
675
676bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
677 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
678}
679
680bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
681 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
682 return true;
683
684 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
685 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
686 TU)))
687 return true;
688 }
689
690 return false;
691}
692
693bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
694 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
695 return true;
696
697 if (TL.hasProtocolsAsWritten()) {
698 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
699 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
700 TL.getProtocolLoc(I),
701 TU)))
702 return true;
703 }
704 }
705
706 return false;
707}
708
709bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
710 return Visit(TL.getPointeeLoc());
711}
712
713bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
714 return Visit(TL.getPointeeLoc());
715}
716
717bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
718 return Visit(TL.getPointeeLoc());
719}
720
721bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
722 return Visit(TL.getPointeeLoc());
723}
724
725bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
726 return Visit(TL.getPointeeLoc());
727}
728
729bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
730 if (Visit(TL.getResultLoc()))
731 return true;
732
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000733 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
734 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
735 return true;
736
737 return false;
738}
739
740bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
741 if (Visit(TL.getElementLoc()))
742 return true;
743
744 if (Expr *Size = TL.getSizeExpr())
745 return Visit(MakeCXCursor(Size, StmtParent, TU));
746
747 return false;
748}
749
Douglas Gregor2332c112010-01-21 20:48:56 +0000750bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
751 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
752}
753
754bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
755 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
756 return Visit(TSInfo->getTypeLoc());
757
758 return false;
759}
760
Douglas Gregora59e3902010-01-21 23:27:09 +0000761bool CursorVisitor::VisitStmt(Stmt *S) {
762 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
763 Child != ChildEnd; ++Child) {
Daniel Dunbar54d67ca2010-01-25 00:40:30 +0000764 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000765 return true;
766 }
767
768 return false;
769}
770
771bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
772 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
773 D != DEnd; ++D) {
Douglas Gregor263b47b2010-01-25 16:12:32 +0000774 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregora59e3902010-01-21 23:27:09 +0000775 return true;
776 }
777
778 return false;
779}
780
Douglas Gregorf5bab412010-01-22 01:00:11 +0000781bool CursorVisitor::VisitIfStmt(IfStmt *S) {
782 if (VarDecl *Var = S->getConditionVariable()) {
783 if (Visit(MakeCXCursor(Var, TU)))
784 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000785 }
Douglas Gregorf5bab412010-01-22 01:00:11 +0000786
Douglas Gregor263b47b2010-01-25 16:12:32 +0000787 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
788 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000789 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
790 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000791 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
792 return true;
793
794 return false;
795}
796
797bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
798 if (VarDecl *Var = S->getConditionVariable()) {
799 if (Visit(MakeCXCursor(Var, TU)))
800 return true;
Douglas Gregor263b47b2010-01-25 16:12:32 +0000801 }
802
803 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
804 return true;
805 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
806 return true;
807
808 return false;
809}
810
811bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
812 if (VarDecl *Var = S->getConditionVariable()) {
813 if (Visit(MakeCXCursor(Var, TU)))
814 return true;
815 }
816
817 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
818 return true;
819 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +0000820 return true;
821
Douglas Gregor263b47b2010-01-25 16:12:32 +0000822 return false;
823}
824
825bool CursorVisitor::VisitForStmt(ForStmt *S) {
826 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
827 return true;
828 if (VarDecl *Var = S->getConditionVariable()) {
829 if (Visit(MakeCXCursor(Var, TU)))
830 return true;
831 }
832
833 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
834 return true;
835 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
836 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +0000837 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
838 return true;
839
840 return false;
841}
842
Douglas Gregor336fd812010-01-23 00:40:08 +0000843bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
844 if (E->isArgumentType()) {
845 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
846 return Visit(TSInfo->getTypeLoc());
847
848 return false;
849 }
850
851 return VisitExpr(E);
852}
853
854bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
855 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
856 if (Visit(TSInfo->getTypeLoc()))
857 return true;
858
859 return VisitCastExpr(E);
860}
861
862bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
863 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
864 if (Visit(TSInfo->getTypeLoc()))
865 return true;
866
867 return VisitExpr(E);
868}
869
Daniel Dunbar140fce22010-01-12 02:34:07 +0000870CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000871 CXString Str;
872 if (DupString) {
873 Str.Spelling = strdup(String);
874 Str.MustFreeString = 1;
875 } else {
876 Str.Spelling = String;
877 Str.MustFreeString = 0;
878 }
879 return Str;
880}
881
Douglas Gregorfc8ea232010-01-26 17:06:03 +0000882CXString CIndexer::createCXString(llvm::StringRef String, bool DupString) {
883 CXString Result;
884 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
885 char *Spelling = (char *)malloc(String.size() + 1);
886 memmove(Spelling, String.data(), String.size());
887 Spelling[String.size()] = 0;
888 Result.Spelling = Spelling;
889 Result.MustFreeString = 1;
890 } else {
891 Result.Spelling = String.data();
892 Result.MustFreeString = 0;
893 }
894 return Result;
895}
896
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000897extern "C" {
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000898CXIndex clang_createIndex(int excludeDeclarationsFromPCH) {
Douglas Gregora030b7c2010-01-22 20:35:53 +0000899 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000900 if (excludeDeclarationsFromPCH)
901 CIdxr->setOnlyLocalDecls();
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000902 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000903}
904
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000905void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000906 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000907 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000908}
909
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000910void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
911 assert(CIdx && "Passed null CXIndex");
912 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
913 CXXIdx->setUseExternalASTGeneration(value);
914}
915
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000916CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000917 const char *ast_filename,
918 CXDiagnosticCallback diag_callback,
919 CXClientData diag_client_data) {
Steve Naroff50398192009-08-28 15:28:48 +0000920 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000921 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000922
Douglas Gregor5352ac02010-01-28 00:27:43 +0000923 // Configure the diagnostics.
924 DiagnosticOptions DiagOpts;
925 llvm::OwningPtr<Diagnostic> Diags;
926 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
927 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
928 Diags->setClient(&DiagClient);
929
930 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000931 CXXIdx->getOnlyLocalDecls(),
932 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000933}
934
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000935CXTranslationUnit
936clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
937 const char *source_filename,
938 int num_command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000939 const char **command_line_args,
940 unsigned num_unsaved_files,
Douglas Gregor5352ac02010-01-28 00:27:43 +0000941 struct CXUnsavedFile *unsaved_files,
942 CXDiagnosticCallback diag_callback,
943 CXClientData diag_client_data) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000944 assert(CIdx && "Passed null CXIndex");
945 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
946
Douglas Gregor5352ac02010-01-28 00:27:43 +0000947 // Configure the diagnostics.
948 DiagnosticOptions DiagOpts;
949 llvm::OwningPtr<Diagnostic> Diags;
950 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
951 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
952 Diags->setClient(&DiagClient);
953
Douglas Gregor4db64a42010-01-23 00:14:00 +0000954 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
955 for (unsigned I = 0; I != num_unsaved_files; ++I) {
956 const llvm::MemoryBuffer *Buffer
957 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
958 unsaved_files[I].Contents + unsaved_files[I].Length,
959 unsaved_files[I].Filename);
960 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
961 Buffer));
962 }
963
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000964 if (!CXXIdx->getUseExternalASTGeneration()) {
965 llvm::SmallVector<const char *, 16> Args;
966
967 // The 'source_filename' argument is optional. If the caller does not
968 // specify it then it is assumed that the source file is specified
969 // in the actual argument list.
970 if (source_filename)
971 Args.push_back(source_filename);
972 Args.insert(Args.end(), command_line_args,
973 command_line_args + num_command_line_args);
974
Douglas Gregor5352ac02010-01-28 00:27:43 +0000975 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000976
Ted Kremenek29b72842010-01-07 22:49:05 +0000977#ifdef USE_CRASHTRACER
978 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000979#endif
980
Daniel Dunbar94220972009-12-05 02:17:18 +0000981 llvm::OwningPtr<ASTUnit> Unit(
982 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor5352ac02010-01-28 00:27:43 +0000983 *Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +0000984 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000985 CXXIdx->getOnlyLocalDecls(),
Douglas Gregor4db64a42010-01-23 00:14:00 +0000986 /* UseBumpAllocator = */ true,
987 RemappedFiles.data(),
988 RemappedFiles.size()));
Ted Kremenek29b72842010-01-07 22:49:05 +0000989
Daniel Dunbar94220972009-12-05 02:17:18 +0000990 // FIXME: Until we have broader testing, just drop the entire AST if we
991 // encountered an error.
Douglas Gregor5352ac02010-01-28 00:27:43 +0000992 if (NumErrors != Diags->getNumErrors())
Daniel Dunbar94220972009-12-05 02:17:18 +0000993 return 0;
994
995 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000996 }
997
Ted Kremenek139ba862009-10-22 00:03:57 +0000998 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000999 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001000
Ted Kremenek139ba862009-10-22 00:03:57 +00001001 // First add the complete path to the 'clang' executable.
1002 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00001003 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001004
Ted Kremenek139ba862009-10-22 00:03:57 +00001005 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001006 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001007
Ted Kremenek139ba862009-10-22 00:03:57 +00001008 // The 'source_filename' argument is optional. If the caller does not
1009 // specify it then it is assumed that the source file is specified
1010 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001011 if (source_filename)
1012 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +00001013
Steve Naroff37b5ac22009-10-15 20:50:09 +00001014 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +00001015 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +00001016 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +00001017 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +00001018
Douglas Gregor4db64a42010-01-23 00:14:00 +00001019 // Remap any unsaved files to temporary files.
1020 std::vector<llvm::sys::Path> TemporaryFiles;
1021 std::vector<std::string> RemapArgs;
1022 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1023 return 0;
1024
1025 // The pointers into the elements of RemapArgs are stable because we
1026 // won't be adding anything to RemapArgs after this point.
1027 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1028 argv.push_back(RemapArgs[i].c_str());
1029
Ted Kremenek139ba862009-10-22 00:03:57 +00001030 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1031 for (int i = 0; i < num_command_line_args; ++i)
1032 if (const char *arg = command_line_args[i]) {
1033 if (strcmp(arg, "-o") == 0) {
1034 ++i; // Also skip the matching argument.
1035 continue;
1036 }
1037 if (strcmp(arg, "-emit-ast") == 0 ||
1038 strcmp(arg, "-c") == 0 ||
1039 strcmp(arg, "-fsyntax-only") == 0) {
1040 continue;
1041 }
1042
1043 // Keep the argument.
1044 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001045 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001046
Douglas Gregord93256e2010-01-28 06:00:51 +00001047 // Generate a temporary name for the diagnostics file.
1048 char tmpFileResults[L_tmpnam];
1049 char *tmpResultsFileName = tmpnam(tmpFileResults);
1050 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
1051 TemporaryFiles.push_back(DiagnosticsFile);
1052 argv.push_back("-fdiagnostics-binary");
1053
Ted Kremenek139ba862009-10-22 00:03:57 +00001054 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +00001055 argv.push_back(NULL);
1056
Ted Kremenekfeb15e32009-10-26 22:14:08 +00001057 // Invoke 'clang'.
1058 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1059 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +00001060 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +00001061 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1062 NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +00001063 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001064 /* redirects */ &Redirects[0],
Ted Kremenek379afec2009-10-22 03:24:01 +00001065 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001066
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001067 if (!ErrMsg.empty()) {
1068 std::string AllArgs;
Ted Kremenek379afec2009-10-22 03:24:01 +00001069 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001070 I != E; ++I) {
1071 AllArgs += ' ';
Ted Kremenek779e5f42009-10-26 22:08:39 +00001072 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001073 AllArgs += *I;
Ted Kremenek779e5f42009-10-26 22:08:39 +00001074 }
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001075
1076 Diags->Report(diag::err_fe_clang) << AllArgs << ErrMsg;
Ted Kremenek379afec2009-10-22 03:24:01 +00001077 }
Benjamin Kramer0829a832009-10-18 11:19:36 +00001078
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001079 // FIXME: Parse the (redirected) standard error to emit diagnostics.
1080
Douglas Gregor5352ac02010-01-28 00:27:43 +00001081 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001082 CXXIdx->getOnlyLocalDecls(),
1083 /* UseBumpAllocator = */ true,
1084 RemappedFiles.data(),
1085 RemappedFiles.size());
Steve Naroffe56b4ba2009-10-20 14:46:24 +00001086 if (ATU)
1087 ATU->unlinkTemporaryFile();
Douglas Gregor4db64a42010-01-23 00:14:00 +00001088
Douglas Gregord93256e2010-01-28 06:00:51 +00001089 ReportSerializedDiagnostics(DiagnosticsFile, *Diags,
1090 num_unsaved_files, unsaved_files);
1091
Douglas Gregor4db64a42010-01-23 00:14:00 +00001092 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1093 TemporaryFiles[i].eraseFromDisk();
1094
Steve Naroffe19944c2009-10-15 22:23:48 +00001095 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00001096}
1097
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001098void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00001099 assert(CTUnit && "Passed null CXTranslationUnit");
1100 delete static_cast<ASTUnit *>(CTUnit);
1101}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001102
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001103CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001104 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +00001105 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +00001106 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1107 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00001108}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00001109
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001110CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001111 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001112 return Result;
1113}
1114
Ted Kremenekfb480492010-01-13 21:46:36 +00001115} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00001116
Ted Kremenekfb480492010-01-13 21:46:36 +00001117//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00001118// CXSourceLocation and CXSourceRange Operations.
1119//===----------------------------------------------------------------------===//
1120
Douglas Gregorb9790342010-01-22 21:44:22 +00001121extern "C" {
1122CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001123 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00001124 return Result;
1125}
1126
1127unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
1128 return loc1.ptr_data == loc2.ptr_data && loc1.int_data == loc2.int_data;
1129}
1130
1131CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1132 CXFile file,
1133 unsigned line,
1134 unsigned column) {
1135 if (!tu)
1136 return clang_getNullLocation();
1137
1138 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1139 SourceLocation SLoc
1140 = CXXUnit->getSourceManager().getLocation(
1141 static_cast<const FileEntry *>(file),
1142 line, column);
1143
Ted Kremeneka297de22010-01-25 22:34:44 +00001144 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc, false);
Douglas Gregorb9790342010-01-22 21:44:22 +00001145}
1146
Douglas Gregor5352ac02010-01-28 00:27:43 +00001147CXSourceRange clang_getNullRange() {
1148 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1149 return Result;
1150}
Douglas Gregorb9790342010-01-22 21:44:22 +00001151
Douglas Gregor5352ac02010-01-28 00:27:43 +00001152CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1153 if (begin.ptr_data[0] != end.ptr_data[0] ||
1154 begin.ptr_data[1] != end.ptr_data[1])
1155 return clang_getNullRange();
1156
1157 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1158 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00001159 return Result;
1160}
1161
Douglas Gregor46766dc2010-01-26 19:19:08 +00001162void clang_getInstantiationLocation(CXSourceLocation location,
1163 CXFile *file,
1164 unsigned *line,
1165 unsigned *column,
1166 unsigned *offset) {
Ted Kremeneka297de22010-01-25 22:34:44 +00001167 cxloc::CXSourceLocationPtr Ptr
Douglas Gregor5352ac02010-01-28 00:27:43 +00001168 = cxloc::CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001169 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1170
Douglas Gregor46766dc2010-01-26 19:19:08 +00001171 if (!Ptr.getPointer() || Loc.isInvalid()) {
1172 if (file)
1173 *file = 0;
1174 if (line)
1175 *line = 0;
1176 if (column)
1177 *column = 0;
1178 if (offset)
1179 *offset = 0;
1180 return;
1181 }
1182
Douglas Gregor1db19de2010-01-19 21:36:55 +00001183 // FIXME: This is largely copy-paste from
1184 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
1185 // what we want the two routines should be refactored.
Douglas Gregor5352ac02010-01-28 00:27:43 +00001186 const SourceManager &SM = *Ptr.getPointer();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001187 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1188
1189 if (Ptr.getInt()) {
1190 // We want the last character in this location, so we will adjust
1191 // the instantiation location accordingly.
1192
1193 // If the location is from a macro instantiation, get the end of
1194 // the instantiation range.
1195 if (Loc.isMacroID())
1196 InstLoc = SM.getInstantiationRange(Loc).second;
1197
1198 // Measure the length token we're pointing at, so we can adjust
1199 // the physical location in the file to point at the last
1200 // character.
1201 // FIXME: This won't cope with trigraphs or escaped newlines
1202 // well. For that, we actually need a preprocessor, which isn't
1203 // currently available here. Eventually, we'll switch the pointer
1204 // data of CXSourceLocation/CXSourceRange to a translation unit
1205 // (CXXUnit), so that the preprocessor will be available here. At
1206 // that point, we can use Preprocessor::getLocForEndOfToken().
1207 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
Douglas Gregor5352ac02010-01-28 00:27:43 +00001208 *static_cast<LangOptions *>(location.ptr_data[1]));
Douglas Gregor1db19de2010-01-19 21:36:55 +00001209 if (Length > 0)
1210 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
1211 }
1212
1213 if (file)
1214 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1215 if (line)
1216 *line = SM.getInstantiationLineNumber(InstLoc);
1217 if (column)
1218 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00001219 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00001220 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00001221}
1222
Douglas Gregor1db19de2010-01-19 21:36:55 +00001223CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001224 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1225 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001226 return Result;
1227}
1228
1229CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Douglas Gregor5352ac02010-01-28 00:27:43 +00001230 cxloc::CXSourceLocationPtr Ptr;
1231 Ptr.setPointer(static_cast<SourceManager *>(range.ptr_data[0]));
Douglas Gregor1db19de2010-01-19 21:36:55 +00001232 Ptr.setInt(true);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001233 CXSourceLocation Result = { { Ptr.getOpaqueValue(), range.ptr_data[1] },
1234 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00001235 return Result;
1236}
1237
Douglas Gregorb9790342010-01-22 21:44:22 +00001238} // end: extern "C"
1239
Douglas Gregor1db19de2010-01-19 21:36:55 +00001240//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00001241// CXFile Operations.
1242//===----------------------------------------------------------------------===//
1243
1244extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +00001245const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001246 if (!SFile)
1247 return 0;
1248
Steve Naroff88145032009-10-27 14:35:18 +00001249 assert(SFile && "Passed null CXFile");
1250 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1251 return FEnt->getName();
1252}
1253
1254time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00001255 if (!SFile)
1256 return 0;
1257
Steve Naroff88145032009-10-27 14:35:18 +00001258 assert(SFile && "Passed null CXFile");
1259 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1260 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00001261}
Douglas Gregorb9790342010-01-22 21:44:22 +00001262
1263CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1264 if (!tu)
1265 return 0;
1266
1267 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1268
1269 FileManager &FMgr = CXXUnit->getFileManager();
1270 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1271 return const_cast<FileEntry *>(File);
1272}
1273
Ted Kremenekfb480492010-01-13 21:46:36 +00001274} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00001275
Ted Kremenekfb480492010-01-13 21:46:36 +00001276//===----------------------------------------------------------------------===//
1277// CXCursor Operations.
1278//===----------------------------------------------------------------------===//
1279
Ted Kremenekfb480492010-01-13 21:46:36 +00001280static Decl *getDeclFromExpr(Stmt *E) {
1281 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1282 return RefExpr->getDecl();
1283 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1284 return ME->getMemberDecl();
1285 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1286 return RE->getDecl();
1287
1288 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1289 return getDeclFromExpr(CE->getCallee());
1290 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1291 return getDeclFromExpr(CE->getSubExpr());
1292 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1293 return OME->getMethodDecl();
1294
1295 return 0;
1296}
1297
1298extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +00001299
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001300unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00001301 CXCursorVisitor visitor,
1302 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001303 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001304
1305 unsigned PCHLevel = Decl::MaxPCHLevel;
1306
1307 // Set the PCHLevel to filter out unwanted decls if requested.
1308 if (CXXUnit->getOnlyLocalDecls()) {
1309 PCHLevel = 0;
1310
1311 // If the main input was an AST, bump the level.
1312 if (CXXUnit->isMainFileAST())
1313 ++PCHLevel;
1314 }
1315
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001316 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregorb1373d02010-01-20 20:59:29 +00001317 return CursorVis.VisitChildren(parent);
1318}
1319
Douglas Gregor78205d42010-01-20 21:45:58 +00001320static CXString getDeclSpelling(Decl *D) {
1321 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1322 if (!ND)
1323 return CIndexer::createCXString("");
1324
1325 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1326 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1327 true);
1328
1329 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1330 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1331 // and returns different names. NamedDecl returns the class name and
1332 // ObjCCategoryImplDecl returns the category name.
1333 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1334
1335 if (ND->getIdentifier())
1336 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1337
1338 return CIndexer::createCXString("");
1339}
1340
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001341CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +00001342 assert(getCursorDecl(C) && "CXCursor has null decl");
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001343 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001344 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001345
Steve Narofff334b4e2009-09-02 18:26:48 +00001346 if (clang_isReference(C.kind)) {
1347 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001348 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00001349 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1350 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001351 }
1352 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00001353 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1354 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001355 }
1356 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001357 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00001358 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +00001359 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00001360 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001361 case CXCursor_TypeRef: {
1362 TypeDecl *Type = getCursorTypeRef(C).first;
1363 assert(Type && "Missing type decl");
1364
1365 return CIndexer::createCXString(
1366 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1367 true);
1368 }
1369
Daniel Dunbaracca7252009-11-30 20:42:49 +00001370 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +00001371 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00001372 }
1373 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001374
1375 if (clang_isExpression(C.kind)) {
1376 Decl *D = getDeclFromExpr(getCursorExpr(C));
1377 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00001378 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +00001379 return CIndexer::createCXString("");
1380 }
1381
Douglas Gregor60cbfac2010-01-25 16:56:17 +00001382 if (clang_isDeclaration(C.kind))
1383 return getDeclSpelling(getCursorDecl(C));
1384
1385 return CIndexer::createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00001386}
1387
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001388const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00001389 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00001390 case CXCursor_FunctionDecl: return "FunctionDecl";
1391 case CXCursor_TypedefDecl: return "TypedefDecl";
1392 case CXCursor_EnumDecl: return "EnumDecl";
1393 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1394 case CXCursor_StructDecl: return "StructDecl";
1395 case CXCursor_UnionDecl: return "UnionDecl";
1396 case CXCursor_ClassDecl: return "ClassDecl";
1397 case CXCursor_FieldDecl: return "FieldDecl";
1398 case CXCursor_VarDecl: return "VarDecl";
1399 case CXCursor_ParmDecl: return "ParmDecl";
1400 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1401 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1402 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1403 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1404 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1405 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1406 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +00001407 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1408 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +00001409 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001410 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1411 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1412 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001413 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor97b98722010-01-19 23:20:36 +00001414 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1415 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1416 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1417 case CXCursor_CallExpr: return "CallExpr";
1418 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1419 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +00001420 case CXCursor_InvalidFile: return "InvalidFile";
1421 case CXCursor_NoDeclFound: return "NoDeclFound";
1422 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001423 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +00001424 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00001425
1426 llvm_unreachable("Unhandled CXCursorKind");
1427 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +00001428}
Steve Naroff89922f82009-08-31 00:59:03 +00001429
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001430enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1431 CXCursor parent,
1432 CXClientData client_data) {
1433 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1434 *BestCursor = cursor;
1435 return CXChildVisit_Recurse;
1436}
1437
Douglas Gregorb9790342010-01-22 21:44:22 +00001438CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1439 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00001440 return clang_getNullCursor();
Ted Kremenekf4629892010-01-14 01:51:23 +00001441
Douglas Gregorb9790342010-01-22 21:44:22 +00001442 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1443
Ted Kremeneka297de22010-01-25 22:34:44 +00001444 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001445 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1446 if (SLoc.isValid()) {
1447 SourceRange RegionOfInterest(SLoc,
1448 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1449
1450 // FIXME: Would be great to have a "hint" cursor, then walk from that
1451 // hint cursor upward until we find a cursor whose source range encloses
1452 // the region of interest, rather than starting from the translation unit.
1453 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1454 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1455 Decl::MaxPCHLevel, RegionOfInterest);
1456 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00001457 }
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001458 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00001459}
1460
Ted Kremenek73885552009-11-17 19:28:59 +00001461CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00001462 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00001463}
1464
1465unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001466 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00001467}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001468
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001469unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00001470 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1471}
1472
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001473unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00001474 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1475}
Steve Naroff2d4d6292009-08-31 14:26:51 +00001476
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001477unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00001478 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1479}
1480
Douglas Gregor97b98722010-01-19 23:20:36 +00001481unsigned clang_isExpression(enum CXCursorKind K) {
1482 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1483}
1484
1485unsigned clang_isStatement(enum CXCursorKind K) {
1486 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1487}
1488
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00001489unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1490 return K == CXCursor_TranslationUnit;
1491}
1492
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001493CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00001494 return C.kind;
1495}
1496
Douglas Gregor97b98722010-01-19 23:20:36 +00001497static SourceLocation getLocationFromExpr(Expr *E) {
1498 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1499 return /*FIXME:*/Msg->getLeftLoc();
1500 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1501 return DRE->getLocation();
1502 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1503 return Member->getMemberLoc();
1504 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1505 return Ivar->getLocation();
1506 return E->getLocStart();
1507}
1508
Douglas Gregor98258af2010-01-18 22:46:11 +00001509CXSourceLocation clang_getCursorLocation(CXCursor C) {
1510 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001511 switch (C.kind) {
1512 case CXCursor_ObjCSuperClassRef: {
1513 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1514 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001515 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001516 }
1517
1518 case CXCursor_ObjCProtocolRef: {
1519 std::pair<ObjCProtocolDecl *, SourceLocation> P
1520 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001521 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001522 }
1523
1524 case CXCursor_ObjCClassRef: {
1525 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1526 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001527 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001528 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001529
1530 case CXCursor_TypeRef: {
1531 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001532 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001533 }
Douglas Gregorf46034a2010-01-18 23:41:10 +00001534
Douglas Gregorf46034a2010-01-18 23:41:10 +00001535 default:
1536 // FIXME: Need a way to enumerate all non-reference cases.
1537 llvm_unreachable("Missed a reference kind");
1538 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001539 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001540
1541 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001542 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001543 getLocationFromExpr(getCursorExpr(C)));
1544
Douglas Gregor5352ac02010-01-28 00:27:43 +00001545 if (!getCursorDecl(C))
1546 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00001547
Douglas Gregorf46034a2010-01-18 23:41:10 +00001548 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001549 SourceLocation Loc = D->getLocation();
1550 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1551 Loc = Class->getClassLoc();
Ted Kremeneka297de22010-01-25 22:34:44 +00001552 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001553}
Douglas Gregora7bde202010-01-19 00:34:46 +00001554
1555CXSourceRange clang_getCursorExtent(CXCursor C) {
1556 if (clang_isReference(C.kind)) {
1557 switch (C.kind) {
1558 case CXCursor_ObjCSuperClassRef: {
1559 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1560 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001561 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001562 }
1563
1564 case CXCursor_ObjCProtocolRef: {
1565 std::pair<ObjCProtocolDecl *, SourceLocation> P
1566 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001567 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001568 }
1569
1570 case CXCursor_ObjCClassRef: {
1571 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1572 = getCursorObjCClassRef(C);
1573
Ted Kremeneka297de22010-01-25 22:34:44 +00001574 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregora7bde202010-01-19 00:34:46 +00001575 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001576
1577 case CXCursor_TypeRef: {
1578 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001579 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001580 }
Douglas Gregora7bde202010-01-19 00:34:46 +00001581
Douglas Gregora7bde202010-01-19 00:34:46 +00001582 default:
1583 // FIXME: Need a way to enumerate all non-reference cases.
1584 llvm_unreachable("Missed a reference kind");
1585 }
1586 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001587
1588 if (clang_isExpression(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001589 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00001590 getCursorExpr(C)->getSourceRange());
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001591
1592 if (clang_isStatement(C.kind))
Ted Kremeneka297de22010-01-25 22:34:44 +00001593 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor33e9abd2010-01-22 19:49:59 +00001594 getCursorStmt(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001595
Douglas Gregor5352ac02010-01-28 00:27:43 +00001596 if (!getCursorDecl(C))
1597 return clang_getNullRange();
Douglas Gregora7bde202010-01-19 00:34:46 +00001598
1599 Decl *D = getCursorDecl(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00001600 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001601}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001602
1603CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001604 if (clang_isInvalid(C.kind))
1605 return clang_getNullCursor();
1606
1607 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregorb6998662010-01-19 19:34:47 +00001608 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001609 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001610
Douglas Gregor97b98722010-01-19 23:20:36 +00001611 if (clang_isExpression(C.kind)) {
1612 Decl *D = getDeclFromExpr(getCursorExpr(C));
1613 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001614 return MakeCXCursor(D, CXXUnit);
Douglas Gregor97b98722010-01-19 23:20:36 +00001615 return clang_getNullCursor();
1616 }
1617
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001618 if (!clang_isReference(C.kind))
1619 return clang_getNullCursor();
1620
1621 switch (C.kind) {
1622 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001623 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001624
1625 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001626 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001627
1628 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001629 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001630
1631 case CXCursor_TypeRef:
1632 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001633
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001634 default:
1635 // We would prefer to enumerate all non-reference cursor kinds here.
1636 llvm_unreachable("Unhandled reference cursor kind");
1637 break;
1638 }
1639 }
1640
1641 return clang_getNullCursor();
1642}
1643
Douglas Gregorb6998662010-01-19 19:34:47 +00001644CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001645 if (clang_isInvalid(C.kind))
1646 return clang_getNullCursor();
1647
1648 ASTUnit *CXXUnit = getCursorASTUnit(C);
1649
Douglas Gregorb6998662010-01-19 19:34:47 +00001650 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001651 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001652 C = clang_getCursorReferenced(C);
1653 WasReference = true;
1654 }
1655
1656 if (!clang_isDeclaration(C.kind))
1657 return clang_getNullCursor();
1658
1659 Decl *D = getCursorDecl(C);
1660 if (!D)
1661 return clang_getNullCursor();
1662
1663 switch (D->getKind()) {
1664 // Declaration kinds that don't really separate the notions of
1665 // declaration and definition.
1666 case Decl::Namespace:
1667 case Decl::Typedef:
1668 case Decl::TemplateTypeParm:
1669 case Decl::EnumConstant:
1670 case Decl::Field:
1671 case Decl::ObjCIvar:
1672 case Decl::ObjCAtDefsField:
1673 case Decl::ImplicitParam:
1674 case Decl::ParmVar:
1675 case Decl::NonTypeTemplateParm:
1676 case Decl::TemplateTemplateParm:
1677 case Decl::ObjCCategoryImpl:
1678 case Decl::ObjCImplementation:
1679 case Decl::LinkageSpec:
1680 case Decl::ObjCPropertyImpl:
1681 case Decl::FileScopeAsm:
1682 case Decl::StaticAssert:
1683 case Decl::Block:
1684 return C;
1685
1686 // Declaration kinds that don't make any sense here, but are
1687 // nonetheless harmless.
1688 case Decl::TranslationUnit:
1689 case Decl::Template:
1690 case Decl::ObjCContainer:
1691 break;
1692
1693 // Declaration kinds for which the definition is not resolvable.
1694 case Decl::UnresolvedUsingTypename:
1695 case Decl::UnresolvedUsingValue:
1696 break;
1697
1698 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001699 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1700 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001701
1702 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001703 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001704
1705 case Decl::Enum:
1706 case Decl::Record:
1707 case Decl::CXXRecord:
1708 case Decl::ClassTemplateSpecialization:
1709 case Decl::ClassTemplatePartialSpecialization:
1710 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001711 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001712 return clang_getNullCursor();
1713
1714 case Decl::Function:
1715 case Decl::CXXMethod:
1716 case Decl::CXXConstructor:
1717 case Decl::CXXDestructor:
1718 case Decl::CXXConversion: {
1719 const FunctionDecl *Def = 0;
1720 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001721 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001722 return clang_getNullCursor();
1723 }
1724
1725 case Decl::Var: {
1726 VarDecl *Var = cast<VarDecl>(D);
1727
1728 // Variables with initializers have definitions.
1729 const VarDecl *Def = 0;
1730 if (Var->getDefinition(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001731 return MakeCXCursor(const_cast<VarDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001732
1733 // extern and private_extern variables are not definitions.
1734 if (Var->hasExternalStorage())
1735 return clang_getNullCursor();
1736
1737 // In-line static data members do not have definitions.
1738 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1739 return clang_getNullCursor();
1740
1741 // All other variables are themselves definitions.
1742 return C;
1743 }
1744
1745 case Decl::FunctionTemplate: {
1746 const FunctionDecl *Def = 0;
1747 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001748 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001749 return clang_getNullCursor();
1750 }
1751
1752 case Decl::ClassTemplate: {
1753 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1754 ->getDefinition(D->getASTContext()))
1755 return MakeCXCursor(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001756 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1757 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001758 return clang_getNullCursor();
1759 }
1760
1761 case Decl::Using: {
1762 UsingDecl *Using = cast<UsingDecl>(D);
1763 CXCursor Def = clang_getNullCursor();
1764 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1765 SEnd = Using->shadow_end();
1766 S != SEnd; ++S) {
1767 if (Def != clang_getNullCursor()) {
1768 // FIXME: We have no way to return multiple results.
1769 return clang_getNullCursor();
1770 }
1771
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001772 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1773 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001774 }
1775
1776 return Def;
1777 }
1778
1779 case Decl::UsingShadow:
1780 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001781 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1782 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001783
1784 case Decl::ObjCMethod: {
1785 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1786 if (Method->isThisDeclarationADefinition())
1787 return C;
1788
1789 // Dig out the method definition in the associated
1790 // @implementation, if we have it.
1791 // FIXME: The ASTs should make finding the definition easier.
1792 if (ObjCInterfaceDecl *Class
1793 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1794 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1795 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1796 Method->isInstanceMethod()))
1797 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001798 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001799
1800 return clang_getNullCursor();
1801 }
1802
1803 case Decl::ObjCCategory:
1804 if (ObjCCategoryImplDecl *Impl
1805 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001806 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001807 return clang_getNullCursor();
1808
1809 case Decl::ObjCProtocol:
1810 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1811 return C;
1812 return clang_getNullCursor();
1813
1814 case Decl::ObjCInterface:
1815 // There are two notions of a "definition" for an Objective-C
1816 // class: the interface and its implementation. When we resolved a
1817 // reference to an Objective-C class, produce the @interface as
1818 // the definition; when we were provided with the interface,
1819 // produce the @implementation as the definition.
1820 if (WasReference) {
1821 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1822 return C;
1823 } else if (ObjCImplementationDecl *Impl
1824 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001825 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001826 return clang_getNullCursor();
1827
1828 case Decl::ObjCProperty:
1829 // FIXME: We don't really know where to find the
1830 // ObjCPropertyImplDecls that implement this property.
1831 return clang_getNullCursor();
1832
1833 case Decl::ObjCCompatibleAlias:
1834 if (ObjCInterfaceDecl *Class
1835 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1836 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001837 return MakeCXCursor(Class, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001838
1839 return clang_getNullCursor();
1840
1841 case Decl::ObjCForwardProtocol: {
1842 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1843 if (Forward->protocol_size() == 1)
1844 return clang_getCursorDefinition(
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001845 MakeCXCursor(*Forward->protocol_begin(),
1846 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001847
1848 // FIXME: Cannot return multiple definitions.
1849 return clang_getNullCursor();
1850 }
1851
1852 case Decl::ObjCClass: {
1853 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1854 if (Class->size() == 1) {
1855 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1856 if (!IFace->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001857 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00001858 return clang_getNullCursor();
1859 }
1860
1861 // FIXME: Cannot return multiple definitions.
1862 return clang_getNullCursor();
1863 }
1864
1865 case Decl::Friend:
1866 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001867 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001868 return clang_getNullCursor();
1869
1870 case Decl::FriendTemplate:
1871 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001872 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00001873 return clang_getNullCursor();
1874 }
1875
1876 return clang_getNullCursor();
1877}
1878
1879unsigned clang_isCursorDefinition(CXCursor C) {
1880 if (!clang_isDeclaration(C.kind))
1881 return 0;
1882
1883 return clang_getCursorDefinition(C) == C;
1884}
1885
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001886void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001887 const char **startBuf,
1888 const char **endBuf,
1889 unsigned *startLine,
1890 unsigned *startColumn,
1891 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001892 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001893 assert(getCursorDecl(C) && "CXCursor has null decl");
1894 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001895 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1896 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001897
Steve Naroff4ade6d62009-09-23 17:52:52 +00001898 SourceManager &SM = FD->getASTContext().getSourceManager();
1899 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1900 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1901 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1902 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1903 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1904 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1905}
Ted Kremenekfb480492010-01-13 21:46:36 +00001906
1907} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001908
Ted Kremenekfb480492010-01-13 21:46:36 +00001909//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001910// Token-based Operations.
1911//===----------------------------------------------------------------------===//
1912
1913/* CXToken layout:
1914 * int_data[0]: a CXTokenKind
1915 * int_data[1]: starting token location
1916 * int_data[2]: token length
1917 * int_data[3]: reserved
1918 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
1919 * otherwise unused.
1920 */
1921extern "C" {
1922
1923CXTokenKind clang_getTokenKind(CXToken CXTok) {
1924 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1925}
1926
1927CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1928 switch (clang_getTokenKind(CXTok)) {
1929 case CXToken_Identifier:
1930 case CXToken_Keyword:
1931 // We know we have an IdentifierInfo*, so use that.
1932 return CIndexer::createCXString(
1933 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
1934
1935 case CXToken_Literal: {
1936 // We have stashed the starting pointer in the ptr_data field. Use it.
1937 const char *Text = static_cast<const char *>(CXTok.ptr_data);
1938 return CIndexer::createCXString(llvm::StringRef(Text, CXTok.int_data[2]),
1939 true);
1940 }
1941
1942 case CXToken_Punctuation:
1943 case CXToken_Comment:
1944 break;
1945 }
1946
1947 // We have to find the starting buffer pointer the hard way, by
1948 // deconstructing the source location.
1949 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1950 if (!CXXUnit)
1951 return CIndexer::createCXString("");
1952
1953 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1954 std::pair<FileID, unsigned> LocInfo
1955 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1956 std::pair<const char *,const char *> Buffer
1957 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1958
1959 return CIndexer::createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1960 CXTok.int_data[2]),
1961 true);
1962}
1963
1964CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1965 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1966 if (!CXXUnit)
1967 return clang_getNullLocation();
1968
1969 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1970 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1971}
1972
1973CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1974 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00001975 if (!CXXUnit)
1976 return clang_getNullRange();
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001977
1978 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
1979 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1980}
1981
1982void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1983 CXToken **Tokens, unsigned *NumTokens) {
1984 if (Tokens)
1985 *Tokens = 0;
1986 if (NumTokens)
1987 *NumTokens = 0;
1988
1989 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1990 if (!CXXUnit || !Tokens || !NumTokens)
1991 return;
1992
1993 SourceRange R = cxloc::translateSourceRange(Range);
1994 if (R.isInvalid())
1995 return;
1996
1997 SourceManager &SourceMgr = CXXUnit->getSourceManager();
1998 std::pair<FileID, unsigned> BeginLocInfo
1999 = SourceMgr.getDecomposedLoc(R.getBegin());
2000 std::pair<FileID, unsigned> EndLocInfo
2001 = SourceMgr.getDecomposedLoc(R.getEnd());
2002
2003 // Cannot tokenize across files.
2004 if (BeginLocInfo.first != EndLocInfo.first)
2005 return;
2006
2007 // Create a lexer
2008 std::pair<const char *,const char *> Buffer
2009 = SourceMgr.getBufferData(BeginLocInfo.first);
2010 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2011 CXXUnit->getASTContext().getLangOptions(),
2012 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
2013 Lex.SetCommentRetentionState(true);
2014
2015 // Lex tokens until we hit the end of the range.
2016 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
2017 llvm::SmallVector<CXToken, 32> CXTokens;
2018 Token Tok;
2019 do {
2020 // Lex the next token
2021 Lex.LexFromRawLexer(Tok);
2022 if (Tok.is(tok::eof))
2023 break;
2024
2025 // Initialize the CXToken.
2026 CXToken CXTok;
2027
2028 // - Common fields
2029 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2030 CXTok.int_data[2] = Tok.getLength();
2031 CXTok.int_data[3] = 0;
2032
2033 // - Kind-specific fields
2034 if (Tok.isLiteral()) {
2035 CXTok.int_data[0] = CXToken_Literal;
2036 CXTok.ptr_data = (void *)Tok.getLiteralData();
2037 } else if (Tok.is(tok::identifier)) {
2038 // Lookup the identifier to determine whether we have a
2039 std::pair<FileID, unsigned> LocInfo
2040 = SourceMgr.getDecomposedLoc(Tok.getLocation());
2041 const char *StartPos
2042 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
2043 LocInfo.second;
2044 IdentifierInfo *II
2045 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2046 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2047 CXToken_Identifier
2048 : CXToken_Keyword;
2049 CXTok.ptr_data = II;
2050 } else if (Tok.is(tok::comment)) {
2051 CXTok.int_data[0] = CXToken_Comment;
2052 CXTok.ptr_data = 0;
2053 } else {
2054 CXTok.int_data[0] = CXToken_Punctuation;
2055 CXTok.ptr_data = 0;
2056 }
2057 CXTokens.push_back(CXTok);
2058 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2059
2060 if (CXTokens.empty())
2061 return;
2062
2063 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2064 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2065 *NumTokens = CXTokens.size();
2066}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002067
2068typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2069
2070enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2071 CXCursor parent,
2072 CXClientData client_data) {
2073 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2074
2075 // We only annotate the locations of declarations, simple
2076 // references, and expressions which directly reference something.
2077 CXCursorKind Kind = clang_getCursorKind(cursor);
2078 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2079 // Okay: We can annotate the location of this declaration with the
2080 // declaration or reference
2081 } else if (clang_isExpression(cursor.kind)) {
2082 if (Kind != CXCursor_DeclRefExpr &&
2083 Kind != CXCursor_MemberRefExpr &&
2084 Kind != CXCursor_ObjCMessageExpr)
2085 return CXChildVisit_Recurse;
2086
2087 CXCursor Referenced = clang_getCursorReferenced(cursor);
2088 if (Referenced == cursor || Referenced == clang_getNullCursor())
2089 return CXChildVisit_Recurse;
2090
2091 // Okay: we can annotate the location of this expression
2092 } else {
2093 // Nothing to annotate
2094 return CXChildVisit_Recurse;
2095 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002096
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002097 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2098 (*Data)[Loc.int_data] = cursor;
2099 return CXChildVisit_Recurse;
2100}
2101
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002102void clang_annotateTokens(CXTranslationUnit TU,
2103 CXToken *Tokens, unsigned NumTokens,
2104 CXCursor *Cursors) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002105 if (NumTokens == 0)
2106 return;
2107
2108 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002109 for (unsigned I = 0; I != NumTokens; ++I)
2110 Cursors[I] = clang_getNullCursor();
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002111
2112 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2113 if (!CXXUnit || !Tokens)
2114 return;
2115
2116 // Annotate all of the source locations in the region of interest that map
2117 SourceRange RegionOfInterest;
2118 RegionOfInterest.setBegin(
2119 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2120 SourceLocation End
2121 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2122 Tokens[NumTokens - 1]));
2123 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End,
2124 1));
2125 // FIXME: Would be great to have a "hint" cursor, then walk from that
2126 // hint cursor upward until we find a cursor whose source range encloses
2127 // the region of interest, rather than starting from the translation unit.
2128 AnnotateTokensData Annotated;
2129 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2130 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2131 Decl::MaxPCHLevel, RegionOfInterest);
2132 AnnotateVis.VisitChildren(Parent);
2133
2134 for (unsigned I = 0; I != NumTokens; ++I) {
2135 // Determine whether we saw a cursor at this token's location.
2136 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2137 if (Pos == Annotated.end())
2138 continue;
2139
2140 Cursors[I] = Pos->second;
2141 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002142}
2143
2144void clang_disposeTokens(CXTranslationUnit TU,
2145 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002146 free(Tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002147}
2148
2149} // end: extern "C"
2150
2151//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002152// CXString Operations.
2153//===----------------------------------------------------------------------===//
2154
2155extern "C" {
2156const char *clang_getCString(CXString string) {
2157 return string.Spelling;
2158}
2159
2160void clang_disposeString(CXString string) {
2161 if (string.MustFreeString && string.Spelling)
2162 free((void*)string.Spelling);
2163}
Ted Kremenek04bb7162010-01-22 22:44:15 +00002164
Ted Kremenekfb480492010-01-13 21:46:36 +00002165} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00002166
2167//===----------------------------------------------------------------------===//
2168// Misc. utility functions.
2169//===----------------------------------------------------------------------===//
2170
2171extern "C" {
2172
2173const char *clang_getClangVersion() {
Ted Kremeneka18f1b82010-01-23 02:11:34 +00002174 return getClangFullVersion();
Ted Kremenek04bb7162010-01-22 22:44:15 +00002175}
2176
2177} // end: extern "C"
2178