blob: 1afd8c23ba140e9fe4e3ccf7933a379d319d1b42 [file] [log] [blame]
Ted Kremenekb60d87c2009-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 Dunbarbbc569c2009-11-30 20:42:43 +00007//
Ted Kremenekb60d87c2009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekb60d87c2009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek87553c42010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek97a45372010-01-25 22:34:44 +000017#include "CXSourceLocation.h"
Douglas Gregor4f9c3762010-01-28 00:27:43 +000018#include "CIndexDiagnostic.h"
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000019
Ted Kremenekc0f3f722010-01-22 22:44:15 +000020#include "clang/Basic/Version.h"
Douglas Gregorba965fb2010-01-28 00:56:43 +000021
Steve Naroffa1c72842009-08-28 15:28:48 +000022#include "clang/AST/DeclVisitor.h"
Steve Naroff66af1ae2009-09-22 19:25:29 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor93f89952010-01-21 16:28:34 +000024#include "clang/AST/TypeLocVisitor.h"
Douglas Gregorba965fb2010-01-28 00:56:43 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenek2a43fd52010-01-06 23:43:31 +000026#include "clang/Lex/Lexer.h"
Douglas Gregor562c1f92010-01-22 19:49:59 +000027#include "clang/Lex/Preprocessor.h"
Douglas Gregord3d923a2009-10-16 21:24:31 +000028#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer2836c4c2009-10-18 11:19:36 +000029#include "llvm/System/Program.h"
Ted Kremenek428c6372009-10-19 21:44:57 +000030
Ted Kremenek902292d2010-01-05 20:55:39 +000031// Needed to define L_TMPNAM on some systems.
32#include <cstdio>
33
Steve Naroffa1c72842009-08-28 15:28:48 +000034using namespace clang;
Ted Kremenek87553c42010-01-15 20:35:54 +000035using namespace clang::cxcursor;
Steve Naroffa1c72842009-08-28 15:28:48 +000036using namespace idx;
37
Ted Kremenek991eb3f2010-01-06 03:42:32 +000038//===----------------------------------------------------------------------===//
39// Crash Reporting.
40//===----------------------------------------------------------------------===//
41
42#ifdef __APPLE__
Ted Kremenek7a5ede22010-01-07 22:49:05 +000043#ifndef NDEBUG
44#define USE_CRASHTRACER
Ted Kremenek991eb3f2010-01-06 03:42:32 +000045#include "clang/Analysis/Support/SaveAndRestore.h"
46// Integrate with crash reporter.
47extern "C" const char *__crashreporter_info__;
Ted Kremenek7a5ede22010-01-07 22:49:05 +000048#define NUM_CRASH_STRINGS 16
49static unsigned crashtracer_counter = 0;
Ted Kremenek32b79312010-01-07 23:13:53 +000050static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek7a5ede22010-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 Kremenek32b79312010-01-07 23:13:53 +000057 unsigned slot = 0;
Ted Kremenek7a5ede22010-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 Kremenek32b79312010-01-07 23:13:53 +000063 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek7a5ede22010-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 Kremenek32b79312010-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 Kremenek7a5ede22010-01-07 22:49:05 +000090 }
Ted Kremenek32b79312010-01-07 23:13:53 +000091
92 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek7a5ede22010-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 Kremenek991eb3f2010-01-06 03:42:32 +0000121#endif
122
Douglas Gregor562c1f92010-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 Gregor4f46e782010-01-19 21:36:55 +0000149
Ted Kremenek991eb3f2010-01-06 03:42:32 +0000150//===----------------------------------------------------------------------===//
Douglas Gregor562c1f92010-01-22 19:49:59 +0000151// Cursor visitor.
Ted Kremenek991eb3f2010-01-06 03:42:32 +0000152//===----------------------------------------------------------------------===//
153
Steve Naroff1054e602009-08-31 00:59:03 +0000154namespace {
Ted Kremenekc2aa0f12010-01-16 00:36:30 +0000155
Douglas Gregor71f3d942010-01-20 20:59:29 +0000156// Cursor visitor.
Douglas Gregor93f89952010-01-21 16:28:34 +0000157class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000158 public TypeLocVisitor<CursorVisitor, bool>,
159 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor93f89952010-01-21 16:28:34 +0000160{
Douglas Gregor562c1f92010-01-22 19:49:59 +0000161 /// \brief The translation unit we are traversing.
Douglas Gregorfed36b12010-01-20 23:57:43 +0000162 ASTUnit *TU;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000163
164 /// \brief The parent cursor whose children we are traversing.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000165 CXCursor Parent;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000166
167 /// \brief The declaration that serves at the parent of any statement or
168 /// expression nodes.
Douglas Gregord1824312010-01-21 17:29:07 +0000169 Decl *StmtParent;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000170
171 /// \brief The visitor function.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000172 CXCursorVisitor Visitor;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000173
174 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000175 CXClientData ClientData;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000176
Douglas Gregor16bef852009-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 Gregor562c1f92010-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 Gregor71f3d942010-01-20 20:59:29 +0000186 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor93f89952010-01-21 16:28:34 +0000187 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000188 using StmtVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor562c1f92010-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 Gregor71f3d942010-01-20 20:59:29 +0000201
Steve Naroff1054e602009-08-31 00:59:03 +0000202public:
Douglas Gregorfed36b12010-01-20 23:57:43 +0000203 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
Douglas Gregor562c1f92010-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 Gregor71f3d942010-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 Gregord1824312010-01-21 17:29:07 +0000213 StmtParent = 0;
Douglas Gregor71f3d942010-01-20 20:59:29 +0000214 }
215
Douglas Gregor562c1f92010-01-22 19:49:59 +0000216 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000217 bool VisitChildren(CXCursor Parent);
218
Douglas Gregor93f89952010-01-21 16:28:34 +0000219 // Declaration visitors
Douglas Gregor71f3d942010-01-20 20:59:29 +0000220 bool VisitDeclContext(DeclContext *DC);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000221 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
Douglas Gregord824f882010-01-22 00:50:27 +0000222 bool VisitTypedefDecl(TypedefDecl *D);
223 bool VisitTagDecl(TagDecl *D);
224 bool VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor93f89952010-01-21 16:28:34 +0000225 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000226 bool VisitFunctionDecl(FunctionDecl *ND);
Douglas Gregord824f882010-01-22 00:50:27 +0000227 bool VisitFieldDecl(FieldDecl *D);
228 bool VisitVarDecl(VarDecl *);
229 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000230 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000231 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000232 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Douglas Gregord824f882010-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 Gregor93f89952010-01-21 16:28:34 +0000242
243 // Type visitors
Douglas Gregord1824312010-01-21 17:29:07 +0000244 // FIXME: QualifiedTypeLoc doesn't provide any location information
245 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor93f89952010-01-21 16:28:34 +0000246 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregord1824312010-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 Gregor6479fc42010-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 Gregor5e8cf372010-01-21 23:27:09 +0000264
265 // Statement visitors
266 bool VisitStmt(Stmt *S);
267 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregore1084fa2010-01-22 01:00:11 +0000268 // FIXME: LabelStmt label?
269 bool VisitIfStmt(IfStmt *S);
270 bool VisitSwitchStmt(SwitchStmt *S);
Douglas Gregor7201f9f2010-01-25 16:12:32 +0000271 bool VisitWhileStmt(WhileStmt *S);
272 bool VisitForStmt(ForStmt *S);
Douglas Gregor625a5152010-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 Naroff1054e602009-08-31 00:59:03 +0000278};
Douglas Gregor71f3d942010-01-20 20:59:29 +0000279
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000280} // end anonymous namespace
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +0000281
Douglas Gregor562c1f92010-01-22 19:49:59 +0000282RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
283 assert(RegionOfInterest.isValid() && "RangeCompare called with invalid range");
284 if (R.isInvalid())
285 return RangeOverlap;
286
287 // Move the end of the input range to the end of the last token in that
288 // range.
Douglas Gregor69ff5dc2010-01-29 00:47:48 +0000289 SourceLocation NewEnd
290 = TU->getPreprocessor().getLocForEndOfToken(R.getEnd(), 1);
291 if (NewEnd.isValid())
292 R.setEnd(NewEnd);
Douglas Gregor562c1f92010-01-22 19:49:59 +0000293 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
294}
295
296RangeComparisonResult CursorVisitor::CompareRegionOfInterest(CXSourceRange CXR) {
Ted Kremenek97a45372010-01-25 22:34:44 +0000297 return CompareRegionOfInterest(cxloc::translateSourceRange(CXR));
Douglas Gregor562c1f92010-01-22 19:49:59 +0000298}
299
Douglas Gregor71f3d942010-01-20 20:59:29 +0000300/// \brief Visit the given cursor and, if requested by the visitor,
301/// its children.
302///
Douglas Gregor562c1f92010-01-22 19:49:59 +0000303/// \param Cursor the cursor to visit.
304///
305/// \param CheckRegionOfInterest if true, then the caller already checked that
306/// this cursor is within the region of interest.
307///
Douglas Gregor71f3d942010-01-20 20:59:29 +0000308/// \returns true if the visitation should be aborted, false if it
309/// should continue.
Douglas Gregor562c1f92010-01-22 19:49:59 +0000310bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregor71f3d942010-01-20 20:59:29 +0000311 if (clang_isInvalid(Cursor.kind))
312 return false;
313
314 if (clang_isDeclaration(Cursor.kind)) {
315 Decl *D = getCursorDecl(Cursor);
316 assert(D && "Invalid declaration cursor");
317 if (D->getPCHLevel() > MaxPCHLevel)
318 return false;
319
320 if (D->isImplicit())
321 return false;
322 }
323
Douglas Gregor562c1f92010-01-22 19:49:59 +0000324 // If we have a range of interest, and this cursor doesn't intersect with it,
325 // we're done.
326 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
327 CXSourceRange Range = clang_getCursorExtent(Cursor);
Ted Kremenek97a45372010-01-25 22:34:44 +0000328 if (cxloc::translateSourceRange(Range).isInvalid() ||
Douglas Gregor562c1f92010-01-22 19:49:59 +0000329 CompareRegionOfInterest(Range))
330 return false;
331 }
332
Douglas Gregor71f3d942010-01-20 20:59:29 +0000333 switch (Visitor(Cursor, Parent, ClientData)) {
334 case CXChildVisit_Break:
335 return true;
336
337 case CXChildVisit_Continue:
338 return false;
339
340 case CXChildVisit_Recurse:
341 return VisitChildren(Cursor);
342 }
343
Douglas Gregor33f16852010-01-25 16:45:46 +0000344 return false;
Douglas Gregor71f3d942010-01-20 20:59:29 +0000345}
346
347/// \brief Visit the children of the given cursor.
348///
349/// \returns true if the visitation should be aborted, false if it
350/// should continue.
351bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000352 if (clang_isReference(Cursor.kind)) {
353 // By definition, references have no children.
354 return false;
355 }
356
Douglas Gregor71f3d942010-01-20 20:59:29 +0000357 // Set the Parent field to Cursor, then back to its old value once we're
358 // done.
359 class SetParentRAII {
360 CXCursor &Parent;
Douglas Gregord1824312010-01-21 17:29:07 +0000361 Decl *&StmtParent;
Douglas Gregor71f3d942010-01-20 20:59:29 +0000362 CXCursor OldParent;
Douglas Gregord1824312010-01-21 17:29:07 +0000363
Douglas Gregor71f3d942010-01-20 20:59:29 +0000364 public:
Douglas Gregord1824312010-01-21 17:29:07 +0000365 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
366 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
Douglas Gregor71f3d942010-01-20 20:59:29 +0000367 {
368 Parent = NewParent;
Douglas Gregord1824312010-01-21 17:29:07 +0000369 if (clang_isDeclaration(Parent.kind))
370 StmtParent = getCursorDecl(Parent);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000371 }
372
373 ~SetParentRAII() {
374 Parent = OldParent;
Douglas Gregord1824312010-01-21 17:29:07 +0000375 if (clang_isDeclaration(Parent.kind))
376 StmtParent = getCursorDecl(Parent);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000377 }
Douglas Gregord1824312010-01-21 17:29:07 +0000378 } SetParent(Parent, StmtParent, Cursor);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000379
380 if (clang_isDeclaration(Cursor.kind)) {
381 Decl *D = getCursorDecl(Cursor);
382 assert(D && "Invalid declaration cursor");
383 return Visit(D);
384 }
385
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000386 if (clang_isStatement(Cursor.kind))
387 return Visit(getCursorStmt(Cursor));
388 if (clang_isExpression(Cursor.kind))
389 return Visit(getCursorExpr(Cursor));
390
Douglas Gregor71f3d942010-01-20 20:59:29 +0000391 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorfed36b12010-01-20 23:57:43 +0000392 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor562c1f92010-01-22 19:49:59 +0000393 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
394 RegionOfInterest.isInvalid()) {
Douglas Gregorbefc4a12010-01-20 21:13:59 +0000395 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
396 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
397 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor562c1f92010-01-22 19:49:59 +0000398 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregorbefc4a12010-01-20 21:13:59 +0000399 return true;
400 }
401 } else {
402 return VisitDeclContext(
Douglas Gregor71f3d942010-01-20 20:59:29 +0000403 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregorbefc4a12010-01-20 21:13:59 +0000404 }
405
406 return false;
Douglas Gregor71f3d942010-01-20 20:59:29 +0000407 }
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000408
Douglas Gregor71f3d942010-01-20 20:59:29 +0000409 // Nothing to visit at the moment.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000410 return false;
411}
412
Douglas Gregor71f3d942010-01-20 20:59:29 +0000413bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenek78668fd2010-01-13 00:22:49 +0000414 for (DeclContext::decl_iterator
Douglas Gregor71f3d942010-01-20 20:59:29 +0000415 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Douglas Gregor562c1f92010-01-22 19:49:59 +0000416 if (RegionOfInterest.isValid()) {
417 SourceRange R = (*I)->getSourceRange();
418 if (R.isInvalid())
419 continue;
420
421 switch (CompareRegionOfInterest(R)) {
422 case RangeBefore:
423 // This declaration comes before the region of interest; skip it.
424 continue;
425
426 case RangeAfter:
427 // This declaration comes after the region of interest; we're done.
428 return false;
429
430 case RangeOverlap:
431 // This declaration overlaps the region of interest; visit it.
432 break;
433 }
434 }
435
436 if (Visit(MakeCXCursor(*I, TU), true))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000437 return true;
438 }
439
440 return false;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000441}
442
Douglas Gregord824f882010-01-22 00:50:27 +0000443bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
444 llvm_unreachable("Translation units are visited directly by Visit()");
445 return false;
446}
447
448bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
449 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
450 return Visit(TSInfo->getTypeLoc());
451
452 return false;
453}
454
455bool CursorVisitor::VisitTagDecl(TagDecl *D) {
456 return VisitDeclContext(D);
457}
458
459bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
460 if (Expr *Init = D->getInitExpr())
461 return Visit(MakeCXCursor(Init, StmtParent, TU));
462 return false;
463}
464
Douglas Gregor93f89952010-01-21 16:28:34 +0000465bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
466 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
467 if (Visit(TSInfo->getTypeLoc()))
468 return true;
469
470 return false;
471}
472
Douglas Gregor71f3d942010-01-20 20:59:29 +0000473bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregord1824312010-01-21 17:29:07 +0000474 if (VisitDeclaratorDecl(ND))
475 return true;
476
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000477 if (ND->isThisDeclarationADefinition() &&
478 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
479 return true;
Douglas Gregor71f3d942010-01-20 20:59:29 +0000480
481 return false;
482}
Ted Kremenek78668fd2010-01-13 00:22:49 +0000483
Douglas Gregord824f882010-01-22 00:50:27 +0000484bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
485 if (VisitDeclaratorDecl(D))
486 return true;
487
488 if (Expr *BitWidth = D->getBitWidth())
489 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
490
491 return false;
492}
493
494bool CursorVisitor::VisitVarDecl(VarDecl *D) {
495 if (VisitDeclaratorDecl(D))
496 return true;
497
498 if (Expr *Init = D->getInit())
499 return Visit(MakeCXCursor(Init, StmtParent, TU));
500
501 return false;
502}
503
504bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
505 // FIXME: We really need a TypeLoc covering Objective-C method declarations.
506 // At the moment, we don't have information about locations in the return
507 // type.
508 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
509 PEnd = ND->param_end();
510 P != PEnd; ++P) {
511 if (Visit(MakeCXCursor(*P, TU)))
512 return true;
513 }
514
515 if (ND->isThisDeclarationADefinition() &&
516 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
517 return true;
518
519 return false;
520}
521
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000522bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
523 return VisitDeclContext(D);
524}
525
Douglas Gregor71f3d942010-01-20 20:59:29 +0000526bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorfed36b12010-01-20 23:57:43 +0000527 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
528 TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000529 return true;
530
Douglas Gregoref6eb842010-01-16 15:44:18 +0000531 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
532 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
533 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorfed36b12010-01-20 23:57:43 +0000534 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000535 return true;
536
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000537 return VisitObjCContainerDecl(ND);
Ted Kremenek78668fd2010-01-13 00:22:49 +0000538}
539
Douglas Gregord824f882010-01-22 00:50:27 +0000540bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
541 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
542 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
543 E = PID->protocol_end(); I != E; ++I, ++PL)
544 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
545 return true;
546
547 return VisitObjCContainerDecl(PID);
548}
549
Douglas Gregor71f3d942010-01-20 20:59:29 +0000550bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenek78668fd2010-01-13 00:22:49 +0000551 // Issue callbacks for super class.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000552 if (D->getSuperClass() &&
553 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Douglas Gregorfed36b12010-01-20 23:57:43 +0000554 D->getSuperClassLoc(),
555 TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000556 return true;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000557
Douglas Gregoref6eb842010-01-16 15:44:18 +0000558 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
559 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
560 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorfed36b12010-01-20 23:57:43 +0000561 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000562 return true;
563
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000564 return VisitObjCContainerDecl(D);
Ted Kremenek78668fd2010-01-13 00:22:49 +0000565}
566
Douglas Gregord824f882010-01-22 00:50:27 +0000567bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
568 return VisitObjCContainerDecl(D);
Ted Kremenek78668fd2010-01-13 00:22:49 +0000569}
570
Douglas Gregord824f882010-01-22 00:50:27 +0000571bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
572 if (Visit(MakeCursorObjCClassRef(D->getCategoryDecl()->getClassInterface(),
573 D->getLocation(), TU)))
574 return true;
575
576 return VisitObjCImplDecl(D);
577}
578
579bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
580#if 0
581 // Issue callbacks for super class.
582 // FIXME: No source location information!
583 if (D->getSuperClass() &&
584 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
585 D->getSuperClassLoc(),
586 TU)))
587 return true;
588#endif
589
590 return VisitObjCImplDecl(D);
591}
592
593bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
594 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
595 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
596 E = D->protocol_end();
597 I != E; ++I, ++PL)
Douglas Gregorfed36b12010-01-20 23:57:43 +0000598 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000599 return true;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000600
Douglas Gregord824f882010-01-22 00:50:27 +0000601 return false;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000602}
603
Douglas Gregord824f882010-01-22 00:50:27 +0000604bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
605 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
606 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
607 return true;
608
609 return false;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000610}
611
Douglas Gregord1824312010-01-21 17:29:07 +0000612bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
613 ASTContext &Context = TU->getASTContext();
614
615 // Some builtin types (such as Objective-C's "id", "sel", and
616 // "Class") have associated declarations. Create cursors for those.
617 QualType VisitType;
618 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
619 case BuiltinType::Void:
620 case BuiltinType::Bool:
621 case BuiltinType::Char_U:
622 case BuiltinType::UChar:
623 case BuiltinType::Char16:
624 case BuiltinType::Char32:
625 case BuiltinType::UShort:
626 case BuiltinType::UInt:
627 case BuiltinType::ULong:
628 case BuiltinType::ULongLong:
629 case BuiltinType::UInt128:
630 case BuiltinType::Char_S:
631 case BuiltinType::SChar:
632 case BuiltinType::WChar:
633 case BuiltinType::Short:
634 case BuiltinType::Int:
635 case BuiltinType::Long:
636 case BuiltinType::LongLong:
637 case BuiltinType::Int128:
638 case BuiltinType::Float:
639 case BuiltinType::Double:
640 case BuiltinType::LongDouble:
641 case BuiltinType::NullPtr:
642 case BuiltinType::Overload:
643 case BuiltinType::Dependent:
644 break;
645
646 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
647 break;
648
649 case BuiltinType::ObjCId:
650 VisitType = Context.getObjCIdType();
651 break;
652
653 case BuiltinType::ObjCClass:
654 VisitType = Context.getObjCClassType();
655 break;
656
657 case BuiltinType::ObjCSel:
658 VisitType = Context.getObjCSelType();
659 break;
660 }
661
662 if (!VisitType.isNull()) {
663 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
664 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
665 TU));
666 }
667
668 return false;
669}
670
Douglas Gregor93f89952010-01-21 16:28:34 +0000671bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
672 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
673}
674
Douglas Gregord1824312010-01-21 17:29:07 +0000675bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
676 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
677}
678
679bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
680 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
681}
682
683bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
684 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
685 return true;
686
687 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
688 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
689 TU)))
690 return true;
691 }
692
693 return false;
694}
695
696bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
697 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc()))
698 return true;
699
700 if (TL.hasProtocolsAsWritten()) {
701 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
702 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I),
703 TL.getProtocolLoc(I),
704 TU)))
705 return true;
706 }
707 }
708
709 return false;
710}
711
712bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
713 return Visit(TL.getPointeeLoc());
714}
715
716bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
717 return Visit(TL.getPointeeLoc());
718}
719
720bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
721 return Visit(TL.getPointeeLoc());
722}
723
724bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
725 return Visit(TL.getPointeeLoc());
726}
727
728bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
729 return Visit(TL.getPointeeLoc());
730}
731
732bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
733 if (Visit(TL.getResultLoc()))
734 return true;
735
Douglas Gregord1824312010-01-21 17:29:07 +0000736 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
737 if (Visit(MakeCXCursor(TL.getArg(I), TU)))
738 return true;
739
740 return false;
741}
742
743bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
744 if (Visit(TL.getElementLoc()))
745 return true;
746
747 if (Expr *Size = TL.getSizeExpr())
748 return Visit(MakeCXCursor(Size, StmtParent, TU));
749
750 return false;
751}
752
Douglas Gregor6479fc42010-01-21 20:48:56 +0000753bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
754 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
755}
756
757bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
758 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
759 return Visit(TSInfo->getTypeLoc());
760
761 return false;
762}
763
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000764bool CursorVisitor::VisitStmt(Stmt *S) {
765 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
766 Child != ChildEnd; ++Child) {
Daniel Dunbar2def7eb2010-01-25 00:40:30 +0000767 if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU)))
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000768 return true;
769 }
770
771 return false;
772}
773
774bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
775 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
776 D != DEnd; ++D) {
Douglas Gregor7201f9f2010-01-25 16:12:32 +0000777 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000778 return true;
779 }
780
781 return false;
782}
783
Douglas Gregore1084fa2010-01-22 01:00:11 +0000784bool CursorVisitor::VisitIfStmt(IfStmt *S) {
785 if (VarDecl *Var = S->getConditionVariable()) {
786 if (Visit(MakeCXCursor(Var, TU)))
787 return true;
Douglas Gregor7201f9f2010-01-25 16:12:32 +0000788 }
Douglas Gregore1084fa2010-01-22 01:00:11 +0000789
Douglas Gregor7201f9f2010-01-25 16:12:32 +0000790 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
791 return true;
Douglas Gregore1084fa2010-01-22 01:00:11 +0000792 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
793 return true;
Douglas Gregore1084fa2010-01-22 01:00:11 +0000794 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
795 return true;
796
797 return false;
798}
799
800bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
801 if (VarDecl *Var = S->getConditionVariable()) {
802 if (Visit(MakeCXCursor(Var, TU)))
803 return true;
Douglas Gregor7201f9f2010-01-25 16:12:32 +0000804 }
805
806 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
807 return true;
808 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
809 return true;
810
811 return false;
812}
813
814bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
815 if (VarDecl *Var = S->getConditionVariable()) {
816 if (Visit(MakeCXCursor(Var, TU)))
817 return true;
818 }
819
820 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
821 return true;
822 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregore1084fa2010-01-22 01:00:11 +0000823 return true;
824
Douglas Gregor7201f9f2010-01-25 16:12:32 +0000825 return false;
826}
827
828bool CursorVisitor::VisitForStmt(ForStmt *S) {
829 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
830 return true;
831 if (VarDecl *Var = S->getConditionVariable()) {
832 if (Visit(MakeCXCursor(Var, TU)))
833 return true;
834 }
835
836 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
837 return true;
838 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
839 return true;
Douglas Gregore1084fa2010-01-22 01:00:11 +0000840 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
841 return true;
842
843 return false;
844}
845
Douglas Gregor625a5152010-01-23 00:40:08 +0000846bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
847 if (E->isArgumentType()) {
848 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
849 return Visit(TSInfo->getTypeLoc());
850
851 return false;
852 }
853
854 return VisitExpr(E);
855}
856
857bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
858 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
859 if (Visit(TSInfo->getTypeLoc()))
860 return true;
861
862 return VisitCastExpr(E);
863}
864
865bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
866 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
867 if (Visit(TSInfo->getTypeLoc()))
868 return true;
869
870 return VisitExpr(E);
871}
872
Daniel Dunbarabd36862010-01-12 02:34:07 +0000873CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer04c99a62009-11-09 19:13:48 +0000874 CXString Str;
875 if (DupString) {
876 Str.Spelling = strdup(String);
877 Str.MustFreeString = 1;
878 } else {
879 Str.Spelling = String;
880 Str.MustFreeString = 0;
881 }
882 return Str;
883}
884
Douglas Gregor27b4fa92010-01-26 17:06:03 +0000885CXString CIndexer::createCXString(llvm::StringRef String, bool DupString) {
886 CXString Result;
887 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
888 char *Spelling = (char *)malloc(String.size() + 1);
889 memmove(Spelling, String.data(), String.size());
890 Spelling[String.size()] = 0;
891 Result.Spelling = Spelling;
892 Result.MustFreeString = 1;
893 } else {
894 Result.Spelling = String.data();
895 Result.MustFreeString = 0;
896 }
897 return Result;
898}
899
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +0000900extern "C" {
Douglas Gregorba965fb2010-01-28 00:56:43 +0000901CXIndex clang_createIndex(int excludeDeclarationsFromPCH) {
Douglas Gregor87752492010-01-22 20:35:53 +0000902 CIndexer *CIdxr = new CIndexer();
Steve Naroff531e2842009-10-20 14:46:24 +0000903 if (excludeDeclarationsFromPCH)
904 CIdxr->setOnlyLocalDecls();
Steve Naroff531e2842009-10-20 14:46:24 +0000905 return CIdxr;
Steve Naroffd5e8e862009-08-27 19:51:58 +0000906}
907
Daniel Dunbar079203f2009-12-01 03:14:51 +0000908void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +0000909 if (CIdx)
910 delete static_cast<CIndexer *>(CIdx);
Steve Naroff3aa2d732009-09-17 18:33:27 +0000911}
912
Daniel Dunbar11089662009-12-03 01:54:28 +0000913void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +0000914 if (CIdx) {
915 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
916 CXXIdx->setUseExternalASTGeneration(value);
917 }
Daniel Dunbar11089662009-12-03 01:54:28 +0000918}
919
Daniel Dunbar079203f2009-12-01 03:14:51 +0000920CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000921 const char *ast_filename,
922 CXDiagnosticCallback diag_callback,
923 CXClientData diag_client_data) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +0000924 if (!CIdx)
925 return 0;
926
Douglas Gregor16bef852009-10-16 20:01:17 +0000927 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000928
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000929 // Configure the diagnostics.
930 DiagnosticOptions DiagOpts;
931 llvm::OwningPtr<Diagnostic> Diags;
932 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
933 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
934 Diags->setClient(&DiagClient);
935
936 return ASTUnit::LoadFromPCHFile(ast_filename, *Diags,
Daniel Dunbar59203002009-12-03 01:45:44 +0000937 CXXIdx->getOnlyLocalDecls(),
938 /* UseBumpAllocator = */ true);
Steve Naroffd5e8e862009-08-27 19:51:58 +0000939}
940
Daniel Dunbar079203f2009-12-01 03:14:51 +0000941CXTranslationUnit
942clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
943 const char *source_filename,
944 int num_command_line_args,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000945 const char **command_line_args,
946 unsigned num_unsaved_files,
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000947 struct CXUnsavedFile *unsaved_files,
948 CXDiagnosticCallback diag_callback,
949 CXClientData diag_client_data) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +0000950 if (!CIdx)
951 return 0;
952
Steve Naroff531e2842009-10-20 14:46:24 +0000953 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
954
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000955 // Configure the diagnostics.
956 DiagnosticOptions DiagOpts;
957 llvm::OwningPtr<Diagnostic> Diags;
958 Diags.reset(CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
959 CIndexDiagnosticClient DiagClient(diag_callback, diag_client_data);
960 Diags->setClient(&DiagClient);
961
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000962 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
963 for (unsigned I = 0; I != num_unsaved_files; ++I) {
964 const llvm::MemoryBuffer *Buffer
965 = llvm::MemoryBuffer::getMemBuffer(unsaved_files[I].Contents,
966 unsaved_files[I].Contents + unsaved_files[I].Length,
967 unsaved_files[I].Filename);
968 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
969 Buffer));
970 }
971
Daniel Dunbar11089662009-12-03 01:54:28 +0000972 if (!CXXIdx->getUseExternalASTGeneration()) {
973 llvm::SmallVector<const char *, 16> Args;
974
975 // The 'source_filename' argument is optional. If the caller does not
976 // specify it then it is assumed that the source file is specified
977 // in the actual argument list.
978 if (source_filename)
979 Args.push_back(source_filename);
980 Args.insert(Args.end(), command_line_args,
981 command_line_args + num_command_line_args);
982
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000983 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenek991eb3f2010-01-06 03:42:32 +0000984
Ted Kremenek7a5ede22010-01-07 22:49:05 +0000985#ifdef USE_CRASHTRACER
986 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek991eb3f2010-01-06 03:42:32 +0000987#endif
988
Daniel Dunbar72fe5b12009-12-05 02:17:18 +0000989 llvm::OwningPtr<ASTUnit> Unit(
990 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000991 *Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +0000992 CXXIdx->getClangResourcesPath(),
Daniel Dunbar72fe5b12009-12-05 02:17:18 +0000993 CXXIdx->getOnlyLocalDecls(),
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000994 /* UseBumpAllocator = */ true,
995 RemappedFiles.data(),
996 RemappedFiles.size()));
Ted Kremenek7a5ede22010-01-07 22:49:05 +0000997
Daniel Dunbar72fe5b12009-12-05 02:17:18 +0000998 // FIXME: Until we have broader testing, just drop the entire AST if we
999 // encountered an error.
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001000 if (NumErrors != Diags->getNumErrors())
Daniel Dunbar72fe5b12009-12-05 02:17:18 +00001001 return 0;
1002
1003 return Unit.take();
Daniel Dunbar11089662009-12-03 01:54:28 +00001004 }
1005
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001006 // Build up the arguments for invoking 'clang'.
Ted Kremenek51d06bb2009-10-15 23:21:22 +00001007 std::vector<const char *> argv;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001008
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001009 // First add the complete path to the 'clang' executable.
1010 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +00001011 argv.push_back(ClangPath.c_str());
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001012
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001013 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek51d06bb2009-10-15 23:21:22 +00001014 argv.push_back("-emit-ast");
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001015
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001016 // The 'source_filename' argument is optional. If the caller does not
1017 // specify it then it is assumed that the source file is specified
1018 // in the actual argument list.
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001019 if (source_filename)
1020 argv.push_back(source_filename);
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001021
Steve Naroff1cfb96c2009-10-15 20:50:09 +00001022 // Generate a temporary name for the AST file.
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001023 argv.push_back("-o");
Steve Naroff1cfb96c2009-10-15 20:50:09 +00001024 char astTmpFile[L_tmpnam];
Ted Kremenek51d06bb2009-10-15 23:21:22 +00001025 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001026
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001027 // Remap any unsaved files to temporary files.
1028 std::vector<llvm::sys::Path> TemporaryFiles;
1029 std::vector<std::string> RemapArgs;
1030 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1031 return 0;
1032
1033 // The pointers into the elements of RemapArgs are stable because we
1034 // won't be adding anything to RemapArgs after this point.
1035 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1036 argv.push_back(RemapArgs[i].c_str());
1037
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001038 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1039 for (int i = 0; i < num_command_line_args; ++i)
1040 if (const char *arg = command_line_args[i]) {
1041 if (strcmp(arg, "-o") == 0) {
1042 ++i; // Also skip the matching argument.
1043 continue;
1044 }
1045 if (strcmp(arg, "-emit-ast") == 0 ||
1046 strcmp(arg, "-c") == 0 ||
1047 strcmp(arg, "-fsyntax-only") == 0) {
1048 continue;
1049 }
1050
1051 // Keep the argument.
1052 argv.push_back(arg);
Steve Naroff531e2842009-10-20 14:46:24 +00001053 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001054
Douglas Gregorac0605e2010-01-28 06:00:51 +00001055 // Generate a temporary name for the diagnostics file.
1056 char tmpFileResults[L_tmpnam];
1057 char *tmpResultsFileName = tmpnam(tmpFileResults);
1058 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
1059 TemporaryFiles.push_back(DiagnosticsFile);
1060 argv.push_back("-fdiagnostics-binary");
1061
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001062 // Add the null terminator.
Ted Kremenek51d06bb2009-10-15 23:21:22 +00001063 argv.push_back(NULL);
1064
Ted Kremenek12e678d2009-10-26 22:14:08 +00001065 // Invoke 'clang'.
1066 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1067 // on Unix or NUL (Windows).
Ted Kremenek44886fd2009-10-22 03:24:01 +00001068 std::string ErrMsg;
Douglas Gregorac0605e2010-01-28 06:00:51 +00001069 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1070 NULL };
Ted Kremenek44886fd2009-10-22 03:24:01 +00001071 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregorba965fb2010-01-28 00:56:43 +00001072 /* redirects */ &Redirects[0],
Ted Kremenek44886fd2009-10-22 03:24:01 +00001073 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001074
Douglas Gregorba965fb2010-01-28 00:56:43 +00001075 if (!ErrMsg.empty()) {
1076 std::string AllArgs;
Ted Kremenek44886fd2009-10-22 03:24:01 +00001077 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregorba965fb2010-01-28 00:56:43 +00001078 I != E; ++I) {
1079 AllArgs += ' ';
Ted Kremenekbf0690c2009-10-26 22:08:39 +00001080 if (*I)
Douglas Gregorba965fb2010-01-28 00:56:43 +00001081 AllArgs += *I;
Ted Kremenekbf0690c2009-10-26 22:08:39 +00001082 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00001083
1084 Diags->Report(diag::err_fe_clang) << AllArgs << ErrMsg;
Ted Kremenek44886fd2009-10-22 03:24:01 +00001085 }
Benjamin Kramer2836c4c2009-10-18 11:19:36 +00001086
Douglas Gregorba965fb2010-01-28 00:56:43 +00001087 // FIXME: Parse the (redirected) standard error to emit diagnostics.
1088
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001089 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, *Diags,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001090 CXXIdx->getOnlyLocalDecls(),
1091 /* UseBumpAllocator = */ true,
1092 RemappedFiles.data(),
1093 RemappedFiles.size());
Steve Naroff531e2842009-10-20 14:46:24 +00001094 if (ATU)
1095 ATU->unlinkTemporaryFile();
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001096
Douglas Gregorac0605e2010-01-28 06:00:51 +00001097 ReportSerializedDiagnostics(DiagnosticsFile, *Diags,
1098 num_unsaved_files, unsaved_files);
1099
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001100 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1101 TemporaryFiles[i].eraseFromDisk();
1102
Steve Naroff44cd60e2009-10-15 22:23:48 +00001103 return ATU;
Steve Naroff7781daa2009-10-15 20:04:39 +00001104}
1105
Daniel Dunbar079203f2009-12-01 03:14:51 +00001106void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001107 if (CTUnit)
1108 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff3aa2d732009-09-17 18:33:27 +00001109}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001110
Daniel Dunbar079203f2009-12-01 03:14:51 +00001111CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001112 if (!CTUnit)
1113 return CIndexer::createCXString("");
1114
Steve Naroffc0683b92009-09-03 18:19:54 +00001115 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek46157972010-01-12 00:36:38 +00001116 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
1117 true);
Steve Naroff38c1a7b2009-09-03 15:49:00 +00001118}
Daniel Dunbare58bd8b2009-08-28 16:30:07 +00001119
Douglas Gregord2fc7272010-01-20 00:23:15 +00001120CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00001121 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregord2fc7272010-01-20 00:23:15 +00001122 return Result;
1123}
1124
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001125} // end: extern "C"
Steve Naroffd5e8e862009-08-27 19:51:58 +00001126
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001127//===----------------------------------------------------------------------===//
Douglas Gregor4f46e782010-01-19 21:36:55 +00001128// CXSourceLocation and CXSourceRange Operations.
1129//===----------------------------------------------------------------------===//
1130
Douglas Gregor816fd362010-01-22 21:44:22 +00001131extern "C" {
1132CXSourceLocation clang_getNullLocation() {
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001133 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregor816fd362010-01-22 21:44:22 +00001134 return Result;
1135}
1136
1137unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
1138 return loc1.ptr_data == loc2.ptr_data && loc1.int_data == loc2.int_data;
1139}
1140
1141CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1142 CXFile file,
1143 unsigned line,
1144 unsigned column) {
1145 if (!tu)
1146 return clang_getNullLocation();
1147
1148 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1149 SourceLocation SLoc
1150 = CXXUnit->getSourceManager().getLocation(
1151 static_cast<const FileEntry *>(file),
1152 line, column);
1153
Ted Kremenek97a45372010-01-25 22:34:44 +00001154 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc, false);
Douglas Gregor816fd362010-01-22 21:44:22 +00001155}
1156
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001157CXSourceRange clang_getNullRange() {
1158 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1159 return Result;
1160}
Douglas Gregor816fd362010-01-22 21:44:22 +00001161
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001162CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1163 if (begin.ptr_data[0] != end.ptr_data[0] ||
1164 begin.ptr_data[1] != end.ptr_data[1])
1165 return clang_getNullRange();
1166
1167 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
1168 begin.int_data, end.int_data };
Douglas Gregor816fd362010-01-22 21:44:22 +00001169 return Result;
1170}
1171
Douglas Gregor9bd6db52010-01-26 19:19:08 +00001172void clang_getInstantiationLocation(CXSourceLocation location,
1173 CXFile *file,
1174 unsigned *line,
1175 unsigned *column,
1176 unsigned *offset) {
Ted Kremenek97a45372010-01-25 22:34:44 +00001177 cxloc::CXSourceLocationPtr Ptr
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001178 = cxloc::CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data[0]);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001179 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1180
Douglas Gregor9bd6db52010-01-26 19:19:08 +00001181 if (!Ptr.getPointer() || Loc.isInvalid()) {
1182 if (file)
1183 *file = 0;
1184 if (line)
1185 *line = 0;
1186 if (column)
1187 *column = 0;
1188 if (offset)
1189 *offset = 0;
1190 return;
1191 }
1192
Douglas Gregor4f46e782010-01-19 21:36:55 +00001193 // FIXME: This is largely copy-paste from
1194 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
1195 // what we want the two routines should be refactored.
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001196 const SourceManager &SM = *Ptr.getPointer();
Douglas Gregor4f46e782010-01-19 21:36:55 +00001197 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
1198
1199 if (Ptr.getInt()) {
1200 // We want the last character in this location, so we will adjust
1201 // the instantiation location accordingly.
1202
1203 // If the location is from a macro instantiation, get the end of
1204 // the instantiation range.
1205 if (Loc.isMacroID())
1206 InstLoc = SM.getInstantiationRange(Loc).second;
1207
1208 // Measure the length token we're pointing at, so we can adjust
1209 // the physical location in the file to point at the last
1210 // character.
1211 // FIXME: This won't cope with trigraphs or escaped newlines
1212 // well. For that, we actually need a preprocessor, which isn't
1213 // currently available here. Eventually, we'll switch the pointer
1214 // data of CXSourceLocation/CXSourceRange to a translation unit
1215 // (CXXUnit), so that the preprocessor will be available here. At
1216 // that point, we can use Preprocessor::getLocForEndOfToken().
1217 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001218 *static_cast<LangOptions *>(location.ptr_data[1]));
Douglas Gregor4f46e782010-01-19 21:36:55 +00001219 if (Length > 0)
1220 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
1221 }
1222
1223 if (file)
1224 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1225 if (line)
1226 *line = SM.getInstantiationLineNumber(InstLoc);
1227 if (column)
1228 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregor47751d62010-01-26 03:07:15 +00001229 if (offset)
Douglas Gregor9bd6db52010-01-26 19:19:08 +00001230 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregor47751d62010-01-26 03:07:15 +00001231}
1232
Douglas Gregor4f46e782010-01-19 21:36:55 +00001233CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001234 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
1235 range.begin_int_data };
Douglas Gregor4f46e782010-01-19 21:36:55 +00001236 return Result;
1237}
1238
1239CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001240 cxloc::CXSourceLocationPtr Ptr;
1241 Ptr.setPointer(static_cast<SourceManager *>(range.ptr_data[0]));
Douglas Gregor4f46e782010-01-19 21:36:55 +00001242 Ptr.setInt(true);
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001243 CXSourceLocation Result = { { Ptr.getOpaqueValue(), range.ptr_data[1] },
1244 range.end_int_data };
Douglas Gregor4f46e782010-01-19 21:36:55 +00001245 return Result;
1246}
1247
Douglas Gregor816fd362010-01-22 21:44:22 +00001248} // end: extern "C"
1249
Douglas Gregor4f46e782010-01-19 21:36:55 +00001250//===----------------------------------------------------------------------===//
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001251// CXFile Operations.
1252//===----------------------------------------------------------------------===//
1253
1254extern "C" {
Steve Naroff6231f182009-10-27 14:35:18 +00001255const char *clang_getFileName(CXFile SFile) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001256 if (!SFile)
1257 return 0;
1258
Steve Naroff6231f182009-10-27 14:35:18 +00001259 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1260 return FEnt->getName();
1261}
1262
1263time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001264 if (!SFile)
1265 return 0;
1266
Steve Naroff6231f182009-10-27 14:35:18 +00001267 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1268 return FEnt->getModificationTime();
Steve Naroff26760892009-09-25 21:45:39 +00001269}
Douglas Gregor816fd362010-01-22 21:44:22 +00001270
1271CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1272 if (!tu)
1273 return 0;
1274
1275 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1276
1277 FileManager &FMgr = CXXUnit->getFileManager();
1278 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1279 return const_cast<FileEntry *>(File);
1280}
1281
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001282} // end: extern "C"
Steve Naroff26760892009-09-25 21:45:39 +00001283
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001284//===----------------------------------------------------------------------===//
1285// CXCursor Operations.
1286//===----------------------------------------------------------------------===//
1287
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001288static Decl *getDeclFromExpr(Stmt *E) {
1289 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1290 return RefExpr->getDecl();
1291 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1292 return ME->getMemberDecl();
1293 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1294 return RE->getDecl();
1295
1296 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1297 return getDeclFromExpr(CE->getCallee());
1298 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1299 return getDeclFromExpr(CE->getSubExpr());
1300 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1301 return OME->getMethodDecl();
1302
1303 return 0;
1304}
1305
1306extern "C" {
Douglas Gregor71f3d942010-01-20 20:59:29 +00001307
Douglas Gregorfed36b12010-01-20 23:57:43 +00001308unsigned clang_visitChildren(CXCursor parent,
Douglas Gregor71f3d942010-01-20 20:59:29 +00001309 CXCursorVisitor visitor,
1310 CXClientData client_data) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00001311 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregor71f3d942010-01-20 20:59:29 +00001312
1313 unsigned PCHLevel = Decl::MaxPCHLevel;
1314
1315 // Set the PCHLevel to filter out unwanted decls if requested.
1316 if (CXXUnit->getOnlyLocalDecls()) {
1317 PCHLevel = 0;
1318
1319 // If the main input was an AST, bump the level.
1320 if (CXXUnit->isMainFileAST())
1321 ++PCHLevel;
1322 }
1323
Douglas Gregorfed36b12010-01-20 23:57:43 +00001324 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregor71f3d942010-01-20 20:59:29 +00001325 return CursorVis.VisitChildren(parent);
1326}
1327
Douglas Gregordd969c82010-01-20 21:45:58 +00001328static CXString getDeclSpelling(Decl *D) {
1329 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1330 if (!ND)
1331 return CIndexer::createCXString("");
1332
1333 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
1334 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
1335 true);
1336
1337 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1338 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1339 // and returns different names. NamedDecl returns the class name and
1340 // ObjCCategoryImplDecl returns the category name.
1341 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
1342
1343 if (ND->getIdentifier())
1344 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
1345
1346 return CIndexer::createCXString("");
1347}
1348
Daniel Dunbar079203f2009-12-01 03:14:51 +00001349CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregord2fc7272010-01-20 00:23:15 +00001350 if (clang_isTranslationUnit(C.kind))
Douglas Gregorfed36b12010-01-20 23:57:43 +00001351 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregord2fc7272010-01-20 00:23:15 +00001352
Steve Naroff80a766b2009-09-02 18:26:48 +00001353 if (clang_isReference(C.kind)) {
1354 switch (C.kind) {
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001355 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor6c8959b2010-01-16 14:00:32 +00001356 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
1357 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001358 }
1359 case CXCursor_ObjCClassRef: {
Douglas Gregor46d66142010-01-16 17:14:40 +00001360 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
1361 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001362 }
1363 case CXCursor_ObjCProtocolRef: {
Douglas Gregoref6eb842010-01-16 15:44:18 +00001364 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001365 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek46157972010-01-12 00:36:38 +00001366 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001367 }
Douglas Gregor93f89952010-01-21 16:28:34 +00001368 case CXCursor_TypeRef: {
1369 TypeDecl *Type = getCursorTypeRef(C).first;
1370 assert(Type && "Missing type decl");
1371
1372 return CIndexer::createCXString(
1373 getCursorContext(C).getTypeDeclType(Type).getAsString().c_str(),
1374 true);
1375 }
1376
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001377 default:
Ted Kremenek46157972010-01-12 00:36:38 +00001378 return CIndexer::createCXString("<not implemented>");
Steve Naroff80a766b2009-09-02 18:26:48 +00001379 }
1380 }
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001381
1382 if (clang_isExpression(C.kind)) {
1383 Decl *D = getDeclFromExpr(getCursorExpr(C));
1384 if (D)
Douglas Gregordd969c82010-01-20 21:45:58 +00001385 return getDeclSpelling(D);
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001386 return CIndexer::createCXString("");
1387 }
1388
Douglas Gregor5bce76c2010-01-25 16:56:17 +00001389 if (clang_isDeclaration(C.kind))
1390 return getDeclSpelling(getCursorDecl(C));
1391
1392 return CIndexer::createCXString("");
Steve Naroff80a766b2009-09-02 18:26:48 +00001393}
1394
Daniel Dunbar079203f2009-12-01 03:14:51 +00001395const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff1054e602009-08-31 00:59:03 +00001396 switch (Kind) {
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001397 case CXCursor_FunctionDecl: return "FunctionDecl";
1398 case CXCursor_TypedefDecl: return "TypedefDecl";
1399 case CXCursor_EnumDecl: return "EnumDecl";
1400 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
1401 case CXCursor_StructDecl: return "StructDecl";
1402 case CXCursor_UnionDecl: return "UnionDecl";
1403 case CXCursor_ClassDecl: return "ClassDecl";
1404 case CXCursor_FieldDecl: return "FieldDecl";
1405 case CXCursor_VarDecl: return "VarDecl";
1406 case CXCursor_ParmDecl: return "ParmDecl";
1407 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
1408 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
1409 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
1410 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
1411 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
1412 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
1413 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001414 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
1415 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregoraccb1832010-01-19 22:07:56 +00001416 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001417 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
1418 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
1419 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor93f89952010-01-21 16:28:34 +00001420 case CXCursor_TypeRef: return "TypeRef";
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001421 case CXCursor_UnexposedExpr: return "UnexposedExpr";
1422 case CXCursor_DeclRefExpr: return "DeclRefExpr";
1423 case CXCursor_MemberRefExpr: return "MemberRefExpr";
1424 case CXCursor_CallExpr: return "CallExpr";
1425 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
1426 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001427 case CXCursor_InvalidFile: return "InvalidFile";
1428 case CXCursor_NoDeclFound: return "NoDeclFound";
1429 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregord2fc7272010-01-20 00:23:15 +00001430 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff1054e602009-08-31 00:59:03 +00001431 }
Ted Kremenek4ba52632010-01-16 02:02:09 +00001432
1433 llvm_unreachable("Unhandled CXCursorKind");
1434 return NULL;
Steve Naroffd5e8e862009-08-27 19:51:58 +00001435}
Steve Naroff1054e602009-08-31 00:59:03 +00001436
Douglas Gregor562c1f92010-01-22 19:49:59 +00001437enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1438 CXCursor parent,
1439 CXClientData client_data) {
1440 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1441 *BestCursor = cursor;
1442 return CXChildVisit_Recurse;
1443}
1444
Douglas Gregor816fd362010-01-22 21:44:22 +00001445CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1446 if (!TU)
Ted Kremeneke34cbde2010-01-14 01:51:23 +00001447 return clang_getNullCursor();
Ted Kremeneke34cbde2010-01-14 01:51:23 +00001448
Douglas Gregor816fd362010-01-22 21:44:22 +00001449 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1450
Ted Kremenek97a45372010-01-25 22:34:44 +00001451 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor562c1f92010-01-22 19:49:59 +00001452 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1453 if (SLoc.isValid()) {
1454 SourceRange RegionOfInterest(SLoc,
1455 CXXUnit->getPreprocessor().getLocForEndOfToken(SLoc, 1));
1456
1457 // FIXME: Would be great to have a "hint" cursor, then walk from that
1458 // hint cursor upward until we find a cursor whose source range encloses
1459 // the region of interest, rather than starting from the translation unit.
1460 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
1461 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
1462 Decl::MaxPCHLevel, RegionOfInterest);
1463 CursorVis.VisitChildren(Parent);
Steve Naroff54f22fb2009-09-15 20:25:34 +00001464 }
Douglas Gregor562c1f92010-01-22 19:49:59 +00001465 return Result;
Steve Naroffd5e8e862009-08-27 19:51:58 +00001466}
1467
Ted Kremeneke05d7802009-11-17 19:28:59 +00001468CXCursor clang_getNullCursor(void) {
Douglas Gregor58552bc2010-01-20 23:34:41 +00001469 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremeneke05d7802009-11-17 19:28:59 +00001470}
1471
1472unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregorc58d05b2010-01-15 21:56:13 +00001473 return X == Y;
Ted Kremeneke05d7802009-11-17 19:28:59 +00001474}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001475
Daniel Dunbar079203f2009-12-01 03:14:51 +00001476unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff54f22fb2009-09-15 20:25:34 +00001477 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1478}
1479
Daniel Dunbar079203f2009-12-01 03:14:51 +00001480unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff1054e602009-08-31 00:59:03 +00001481 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1482}
Steve Naroff772c1a42009-08-31 14:26:51 +00001483
Daniel Dunbar079203f2009-12-01 03:14:51 +00001484unsigned clang_isReference(enum CXCursorKind K) {
Steve Naroff80a766b2009-09-02 18:26:48 +00001485 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1486}
1487
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001488unsigned clang_isExpression(enum CXCursorKind K) {
1489 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1490}
1491
1492unsigned clang_isStatement(enum CXCursorKind K) {
1493 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1494}
1495
Douglas Gregord2fc7272010-01-20 00:23:15 +00001496unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1497 return K == CXCursor_TranslationUnit;
1498}
1499
Daniel Dunbar079203f2009-12-01 03:14:51 +00001500CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroffef9618b2009-09-04 15:44:05 +00001501 return C.kind;
1502}
1503
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001504static SourceLocation getLocationFromExpr(Expr *E) {
1505 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1506 return /*FIXME:*/Msg->getLeftLoc();
1507 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1508 return DRE->getLocation();
1509 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1510 return Member->getMemberLoc();
1511 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1512 return Ivar->getLocation();
1513 return E->getLocStart();
1514}
1515
Douglas Gregor66a58812010-01-18 22:46:11 +00001516CXSourceLocation clang_getCursorLocation(CXCursor C) {
1517 if (clang_isReference(C.kind)) {
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001518 switch (C.kind) {
1519 case CXCursor_ObjCSuperClassRef: {
1520 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1521 = getCursorObjCSuperClassRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001522 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001523 }
1524
1525 case CXCursor_ObjCProtocolRef: {
1526 std::pair<ObjCProtocolDecl *, SourceLocation> P
1527 = getCursorObjCProtocolRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001528 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001529 }
1530
1531 case CXCursor_ObjCClassRef: {
1532 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1533 = getCursorObjCClassRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001534 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001535 }
Douglas Gregor93f89952010-01-21 16:28:34 +00001536
1537 case CXCursor_TypeRef: {
1538 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001539 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor93f89952010-01-21 16:28:34 +00001540 }
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001541
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001542 default:
1543 // FIXME: Need a way to enumerate all non-reference cases.
1544 llvm_unreachable("Missed a reference kind");
1545 }
Douglas Gregor66a58812010-01-18 22:46:11 +00001546 }
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001547
1548 if (clang_isExpression(C.kind))
Ted Kremenek97a45372010-01-25 22:34:44 +00001549 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001550 getLocationFromExpr(getCursorExpr(C)));
1551
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001552 if (!getCursorDecl(C))
1553 return clang_getNullLocation();
Douglas Gregor66a58812010-01-18 22:46:11 +00001554
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001555 Decl *D = getCursorDecl(C);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001556 SourceLocation Loc = D->getLocation();
1557 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1558 Loc = Class->getClassLoc();
Ted Kremenek97a45372010-01-25 22:34:44 +00001559 return cxloc::translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001560}
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001561
1562CXSourceRange clang_getCursorExtent(CXCursor C) {
1563 if (clang_isReference(C.kind)) {
1564 switch (C.kind) {
1565 case CXCursor_ObjCSuperClassRef: {
1566 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1567 = getCursorObjCSuperClassRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001568 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001569 }
1570
1571 case CXCursor_ObjCProtocolRef: {
1572 std::pair<ObjCProtocolDecl *, SourceLocation> P
1573 = getCursorObjCProtocolRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001574 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001575 }
1576
1577 case CXCursor_ObjCClassRef: {
1578 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1579 = getCursorObjCClassRef(C);
1580
Ted Kremenek97a45372010-01-25 22:34:44 +00001581 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001582 }
Douglas Gregor93f89952010-01-21 16:28:34 +00001583
1584 case CXCursor_TypeRef: {
1585 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001586 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor93f89952010-01-21 16:28:34 +00001587 }
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001588
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001589 default:
1590 // FIXME: Need a way to enumerate all non-reference cases.
1591 llvm_unreachable("Missed a reference kind");
1592 }
1593 }
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001594
1595 if (clang_isExpression(C.kind))
Ted Kremenek97a45372010-01-25 22:34:44 +00001596 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001597 getCursorExpr(C)->getSourceRange());
Douglas Gregor562c1f92010-01-22 19:49:59 +00001598
1599 if (clang_isStatement(C.kind))
Ted Kremenek97a45372010-01-25 22:34:44 +00001600 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor562c1f92010-01-22 19:49:59 +00001601 getCursorStmt(C)->getSourceRange());
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001602
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001603 if (!getCursorDecl(C))
1604 return clang_getNullRange();
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001605
1606 Decl *D = getCursorDecl(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001607 return cxloc::translateSourceRange(D->getASTContext(), D->getSourceRange());
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001608}
Douglas Gregorad27e8b2010-01-19 01:20:04 +00001609
1610CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00001611 if (clang_isInvalid(C.kind))
1612 return clang_getNullCursor();
1613
1614 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001615 if (clang_isDeclaration(C.kind))
Douglas Gregorad27e8b2010-01-19 01:20:04 +00001616 return C;
Douglas Gregor66a58812010-01-18 22:46:11 +00001617
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001618 if (clang_isExpression(C.kind)) {
1619 Decl *D = getDeclFromExpr(getCursorExpr(C));
1620 if (D)
Douglas Gregorfed36b12010-01-20 23:57:43 +00001621 return MakeCXCursor(D, CXXUnit);
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001622 return clang_getNullCursor();
1623 }
1624
Douglas Gregorad27e8b2010-01-19 01:20:04 +00001625 if (!clang_isReference(C.kind))
1626 return clang_getNullCursor();
1627
1628 switch (C.kind) {
1629 case CXCursor_ObjCSuperClassRef:
Douglas Gregorfed36b12010-01-20 23:57:43 +00001630 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Douglas Gregorad27e8b2010-01-19 01:20:04 +00001631
1632 case CXCursor_ObjCProtocolRef: {
Douglas Gregorfed36b12010-01-20 23:57:43 +00001633 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Douglas Gregorad27e8b2010-01-19 01:20:04 +00001634
1635 case CXCursor_ObjCClassRef:
Douglas Gregorfed36b12010-01-20 23:57:43 +00001636 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor93f89952010-01-21 16:28:34 +00001637
1638 case CXCursor_TypeRef:
1639 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregorad27e8b2010-01-19 01:20:04 +00001640
Douglas Gregorad27e8b2010-01-19 01:20:04 +00001641 default:
1642 // We would prefer to enumerate all non-reference cursor kinds here.
1643 llvm_unreachable("Unhandled reference cursor kind");
1644 break;
1645 }
1646 }
1647
1648 return clang_getNullCursor();
1649}
1650
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001651CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00001652 if (clang_isInvalid(C.kind))
1653 return clang_getNullCursor();
1654
1655 ASTUnit *CXXUnit = getCursorASTUnit(C);
1656
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001657 bool WasReference = false;
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001658 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001659 C = clang_getCursorReferenced(C);
1660 WasReference = true;
1661 }
1662
1663 if (!clang_isDeclaration(C.kind))
1664 return clang_getNullCursor();
1665
1666 Decl *D = getCursorDecl(C);
1667 if (!D)
1668 return clang_getNullCursor();
1669
1670 switch (D->getKind()) {
1671 // Declaration kinds that don't really separate the notions of
1672 // declaration and definition.
1673 case Decl::Namespace:
1674 case Decl::Typedef:
1675 case Decl::TemplateTypeParm:
1676 case Decl::EnumConstant:
1677 case Decl::Field:
1678 case Decl::ObjCIvar:
1679 case Decl::ObjCAtDefsField:
1680 case Decl::ImplicitParam:
1681 case Decl::ParmVar:
1682 case Decl::NonTypeTemplateParm:
1683 case Decl::TemplateTemplateParm:
1684 case Decl::ObjCCategoryImpl:
1685 case Decl::ObjCImplementation:
1686 case Decl::LinkageSpec:
1687 case Decl::ObjCPropertyImpl:
1688 case Decl::FileScopeAsm:
1689 case Decl::StaticAssert:
1690 case Decl::Block:
1691 return C;
1692
1693 // Declaration kinds that don't make any sense here, but are
1694 // nonetheless harmless.
1695 case Decl::TranslationUnit:
1696 case Decl::Template:
1697 case Decl::ObjCContainer:
1698 break;
1699
1700 // Declaration kinds for which the definition is not resolvable.
1701 case Decl::UnresolvedUsingTypename:
1702 case Decl::UnresolvedUsingValue:
1703 break;
1704
1705 case Decl::UsingDirective:
Douglas Gregorfed36b12010-01-20 23:57:43 +00001706 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
1707 CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001708
1709 case Decl::NamespaceAlias:
Douglas Gregorfed36b12010-01-20 23:57:43 +00001710 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001711
1712 case Decl::Enum:
1713 case Decl::Record:
1714 case Decl::CXXRecord:
1715 case Decl::ClassTemplateSpecialization:
1716 case Decl::ClassTemplatePartialSpecialization:
1717 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
Douglas Gregorfed36b12010-01-20 23:57:43 +00001718 return MakeCXCursor(Def, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001719 return clang_getNullCursor();
1720
1721 case Decl::Function:
1722 case Decl::CXXMethod:
1723 case Decl::CXXConstructor:
1724 case Decl::CXXDestructor:
1725 case Decl::CXXConversion: {
1726 const FunctionDecl *Def = 0;
1727 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorfed36b12010-01-20 23:57:43 +00001728 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001729 return clang_getNullCursor();
1730 }
1731
1732 case Decl::Var: {
1733 VarDecl *Var = cast<VarDecl>(D);
1734
1735 // Variables with initializers have definitions.
1736 const VarDecl *Def = 0;
1737 if (Var->getDefinition(Def))
Douglas Gregorfed36b12010-01-20 23:57:43 +00001738 return MakeCXCursor(const_cast<VarDecl *>(Def), CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001739
1740 // extern and private_extern variables are not definitions.
1741 if (Var->hasExternalStorage())
1742 return clang_getNullCursor();
1743
1744 // In-line static data members do not have definitions.
1745 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1746 return clang_getNullCursor();
1747
1748 // All other variables are themselves definitions.
1749 return C;
1750 }
1751
1752 case Decl::FunctionTemplate: {
1753 const FunctionDecl *Def = 0;
1754 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorfed36b12010-01-20 23:57:43 +00001755 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001756 return clang_getNullCursor();
1757 }
1758
1759 case Decl::ClassTemplate: {
1760 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1761 ->getDefinition(D->getASTContext()))
1762 return MakeCXCursor(
Douglas Gregorfed36b12010-01-20 23:57:43 +00001763 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
1764 CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001765 return clang_getNullCursor();
1766 }
1767
1768 case Decl::Using: {
1769 UsingDecl *Using = cast<UsingDecl>(D);
1770 CXCursor Def = clang_getNullCursor();
1771 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1772 SEnd = Using->shadow_end();
1773 S != SEnd; ++S) {
1774 if (Def != clang_getNullCursor()) {
1775 // FIXME: We have no way to return multiple results.
1776 return clang_getNullCursor();
1777 }
1778
Douglas Gregorfed36b12010-01-20 23:57:43 +00001779 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
1780 CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001781 }
1782
1783 return Def;
1784 }
1785
1786 case Decl::UsingShadow:
1787 return clang_getCursorDefinition(
Douglas Gregorfed36b12010-01-20 23:57:43 +00001788 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
1789 CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001790
1791 case Decl::ObjCMethod: {
1792 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1793 if (Method->isThisDeclarationADefinition())
1794 return C;
1795
1796 // Dig out the method definition in the associated
1797 // @implementation, if we have it.
1798 // FIXME: The ASTs should make finding the definition easier.
1799 if (ObjCInterfaceDecl *Class
1800 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1801 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1802 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1803 Method->isInstanceMethod()))
1804 if (Def->isThisDeclarationADefinition())
Douglas Gregorfed36b12010-01-20 23:57:43 +00001805 return MakeCXCursor(Def, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001806
1807 return clang_getNullCursor();
1808 }
1809
1810 case Decl::ObjCCategory:
1811 if (ObjCCategoryImplDecl *Impl
1812 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorfed36b12010-01-20 23:57:43 +00001813 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001814 return clang_getNullCursor();
1815
1816 case Decl::ObjCProtocol:
1817 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1818 return C;
1819 return clang_getNullCursor();
1820
1821 case Decl::ObjCInterface:
1822 // There are two notions of a "definition" for an Objective-C
1823 // class: the interface and its implementation. When we resolved a
1824 // reference to an Objective-C class, produce the @interface as
1825 // the definition; when we were provided with the interface,
1826 // produce the @implementation as the definition.
1827 if (WasReference) {
1828 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1829 return C;
1830 } else if (ObjCImplementationDecl *Impl
1831 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorfed36b12010-01-20 23:57:43 +00001832 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001833 return clang_getNullCursor();
1834
1835 case Decl::ObjCProperty:
1836 // FIXME: We don't really know where to find the
1837 // ObjCPropertyImplDecls that implement this property.
1838 return clang_getNullCursor();
1839
1840 case Decl::ObjCCompatibleAlias:
1841 if (ObjCInterfaceDecl *Class
1842 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1843 if (!Class->isForwardDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00001844 return MakeCXCursor(Class, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001845
1846 return clang_getNullCursor();
1847
1848 case Decl::ObjCForwardProtocol: {
1849 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1850 if (Forward->protocol_size() == 1)
1851 return clang_getCursorDefinition(
Douglas Gregorfed36b12010-01-20 23:57:43 +00001852 MakeCXCursor(*Forward->protocol_begin(),
1853 CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001854
1855 // FIXME: Cannot return multiple definitions.
1856 return clang_getNullCursor();
1857 }
1858
1859 case Decl::ObjCClass: {
1860 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1861 if (Class->size() == 1) {
1862 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1863 if (!IFace->isForwardDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00001864 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001865 return clang_getNullCursor();
1866 }
1867
1868 // FIXME: Cannot return multiple definitions.
1869 return clang_getNullCursor();
1870 }
1871
1872 case Decl::Friend:
1873 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00001874 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001875 return clang_getNullCursor();
1876
1877 case Decl::FriendTemplate:
1878 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00001879 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001880 return clang_getNullCursor();
1881 }
1882
1883 return clang_getNullCursor();
1884}
1885
1886unsigned clang_isCursorDefinition(CXCursor C) {
1887 if (!clang_isDeclaration(C.kind))
1888 return 0;
1889
1890 return clang_getCursorDefinition(C) == C;
1891}
1892
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001893void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff76b8f132009-09-23 17:52:52 +00001894 const char **startBuf,
1895 const char **endBuf,
1896 unsigned *startLine,
1897 unsigned *startColumn,
1898 unsigned *endLine,
Daniel Dunbar079203f2009-12-01 03:14:51 +00001899 unsigned *endColumn) {
Douglas Gregorc58d05b2010-01-15 21:56:13 +00001900 assert(getCursorDecl(C) && "CXCursor has null decl");
1901 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff76b8f132009-09-23 17:52:52 +00001902 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1903 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001904
Steve Naroff76b8f132009-09-23 17:52:52 +00001905 SourceManager &SM = FD->getASTContext().getSourceManager();
1906 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1907 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1908 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1909 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1910 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1911 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1912}
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001913
1914} // end: extern "C"
Steve Naroff76b8f132009-09-23 17:52:52 +00001915
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001916//===----------------------------------------------------------------------===//
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001917// Token-based Operations.
1918//===----------------------------------------------------------------------===//
1919
1920/* CXToken layout:
1921 * int_data[0]: a CXTokenKind
1922 * int_data[1]: starting token location
1923 * int_data[2]: token length
1924 * int_data[3]: reserved
1925 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
1926 * otherwise unused.
1927 */
1928extern "C" {
1929
1930CXTokenKind clang_getTokenKind(CXToken CXTok) {
1931 return static_cast<CXTokenKind>(CXTok.int_data[0]);
1932}
1933
1934CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
1935 switch (clang_getTokenKind(CXTok)) {
1936 case CXToken_Identifier:
1937 case CXToken_Keyword:
1938 // We know we have an IdentifierInfo*, so use that.
1939 return CIndexer::createCXString(
1940 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
1941
1942 case CXToken_Literal: {
1943 // We have stashed the starting pointer in the ptr_data field. Use it.
1944 const char *Text = static_cast<const char *>(CXTok.ptr_data);
1945 return CIndexer::createCXString(llvm::StringRef(Text, CXTok.int_data[2]),
1946 true);
1947 }
1948
1949 case CXToken_Punctuation:
1950 case CXToken_Comment:
1951 break;
1952 }
1953
1954 // We have to find the starting buffer pointer the hard way, by
1955 // deconstructing the source location.
1956 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1957 if (!CXXUnit)
1958 return CIndexer::createCXString("");
1959
1960 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
1961 std::pair<FileID, unsigned> LocInfo
1962 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
1963 std::pair<const char *,const char *> Buffer
1964 = CXXUnit->getSourceManager().getBufferData(LocInfo.first);
1965
1966 return CIndexer::createCXString(llvm::StringRef(Buffer.first+LocInfo.second,
1967 CXTok.int_data[2]),
1968 true);
1969}
1970
1971CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
1972 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1973 if (!CXXUnit)
1974 return clang_getNullLocation();
1975
1976 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
1977 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1978}
1979
1980CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
1981 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001982 if (!CXXUnit)
1983 return clang_getNullRange();
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001984
1985 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
1986 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
1987}
1988
1989void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
1990 CXToken **Tokens, unsigned *NumTokens) {
1991 if (Tokens)
1992 *Tokens = 0;
1993 if (NumTokens)
1994 *NumTokens = 0;
1995
1996 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1997 if (!CXXUnit || !Tokens || !NumTokens)
1998 return;
1999
2000 SourceRange R = cxloc::translateSourceRange(Range);
2001 if (R.isInvalid())
2002 return;
2003
2004 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2005 std::pair<FileID, unsigned> BeginLocInfo
2006 = SourceMgr.getDecomposedLoc(R.getBegin());
2007 std::pair<FileID, unsigned> EndLocInfo
2008 = SourceMgr.getDecomposedLoc(R.getEnd());
2009
2010 // Cannot tokenize across files.
2011 if (BeginLocInfo.first != EndLocInfo.first)
2012 return;
2013
2014 // Create a lexer
2015 std::pair<const char *,const char *> Buffer
2016 = SourceMgr.getBufferData(BeginLocInfo.first);
2017 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2018 CXXUnit->getASTContext().getLangOptions(),
2019 Buffer.first, Buffer.first + BeginLocInfo.second, Buffer.second);
2020 Lex.SetCommentRetentionState(true);
2021
2022 // Lex tokens until we hit the end of the range.
2023 const char *EffectiveBufferEnd = Buffer.first + EndLocInfo.second;
2024 llvm::SmallVector<CXToken, 32> CXTokens;
2025 Token Tok;
2026 do {
2027 // Lex the next token
2028 Lex.LexFromRawLexer(Tok);
2029 if (Tok.is(tok::eof))
2030 break;
2031
2032 // Initialize the CXToken.
2033 CXToken CXTok;
2034
2035 // - Common fields
2036 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2037 CXTok.int_data[2] = Tok.getLength();
2038 CXTok.int_data[3] = 0;
2039
2040 // - Kind-specific fields
2041 if (Tok.isLiteral()) {
2042 CXTok.int_data[0] = CXToken_Literal;
2043 CXTok.ptr_data = (void *)Tok.getLiteralData();
2044 } else if (Tok.is(tok::identifier)) {
2045 // Lookup the identifier to determine whether we have a
2046 std::pair<FileID, unsigned> LocInfo
2047 = SourceMgr.getDecomposedLoc(Tok.getLocation());
2048 const char *StartPos
2049 = CXXUnit->getSourceManager().getBufferData(LocInfo.first).first +
2050 LocInfo.second;
2051 IdentifierInfo *II
2052 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
2053 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2054 CXToken_Identifier
2055 : CXToken_Keyword;
2056 CXTok.ptr_data = II;
2057 } else if (Tok.is(tok::comment)) {
2058 CXTok.int_data[0] = CXToken_Comment;
2059 CXTok.ptr_data = 0;
2060 } else {
2061 CXTok.int_data[0] = CXToken_Punctuation;
2062 CXTok.ptr_data = 0;
2063 }
2064 CXTokens.push_back(CXTok);
2065 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
2066
2067 if (CXTokens.empty())
2068 return;
2069
2070 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2071 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2072 *NumTokens = CXTokens.size();
2073}
Douglas Gregor61656112010-01-26 18:31:56 +00002074
2075typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
2076
2077enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2078 CXCursor parent,
2079 CXClientData client_data) {
2080 AnnotateTokensData *Data = static_cast<AnnotateTokensData *>(client_data);
2081
2082 // We only annotate the locations of declarations, simple
2083 // references, and expressions which directly reference something.
2084 CXCursorKind Kind = clang_getCursorKind(cursor);
2085 if (clang_isDeclaration(Kind) || clang_isReference(Kind)) {
2086 // Okay: We can annotate the location of this declaration with the
2087 // declaration or reference
2088 } else if (clang_isExpression(cursor.kind)) {
2089 if (Kind != CXCursor_DeclRefExpr &&
2090 Kind != CXCursor_MemberRefExpr &&
2091 Kind != CXCursor_ObjCMessageExpr)
2092 return CXChildVisit_Recurse;
2093
2094 CXCursor Referenced = clang_getCursorReferenced(cursor);
2095 if (Referenced == cursor || Referenced == clang_getNullCursor())
2096 return CXChildVisit_Recurse;
2097
2098 // Okay: we can annotate the location of this expression
2099 } else {
2100 // Nothing to annotate
2101 return CXChildVisit_Recurse;
2102 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002103
Douglas Gregor61656112010-01-26 18:31:56 +00002104 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2105 (*Data)[Loc.int_data] = cursor;
2106 return CXChildVisit_Recurse;
2107}
2108
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002109void clang_annotateTokens(CXTranslationUnit TU,
2110 CXToken *Tokens, unsigned NumTokens,
2111 CXCursor *Cursors) {
Douglas Gregor61656112010-01-26 18:31:56 +00002112 if (NumTokens == 0)
2113 return;
2114
2115 // Any token we don't specifically annotate will have a NULL cursor.
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002116 for (unsigned I = 0; I != NumTokens; ++I)
2117 Cursors[I] = clang_getNullCursor();
Douglas Gregor61656112010-01-26 18:31:56 +00002118
2119 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2120 if (!CXXUnit || !Tokens)
2121 return;
2122
2123 // Annotate all of the source locations in the region of interest that map
2124 SourceRange RegionOfInterest;
2125 RegionOfInterest.setBegin(
2126 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
2127 SourceLocation End
2128 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2129 Tokens[NumTokens - 1]));
2130 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End,
2131 1));
2132 // FIXME: Would be great to have a "hint" cursor, then walk from that
2133 // hint cursor upward until we find a cursor whose source range encloses
2134 // the region of interest, rather than starting from the translation unit.
2135 AnnotateTokensData Annotated;
2136 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2137 CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated,
2138 Decl::MaxPCHLevel, RegionOfInterest);
2139 AnnotateVis.VisitChildren(Parent);
2140
2141 for (unsigned I = 0; I != NumTokens; ++I) {
2142 // Determine whether we saw a cursor at this token's location.
2143 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2144 if (Pos == Annotated.end())
2145 continue;
2146
2147 Cursors[I] = Pos->second;
2148 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002149}
2150
2151void clang_disposeTokens(CXTranslationUnit TU,
2152 CXToken *Tokens, unsigned NumTokens) {
Douglas Gregor61656112010-01-26 18:31:56 +00002153 free(Tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002154}
2155
2156} // end: extern "C"
2157
2158//===----------------------------------------------------------------------===//
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002159// CXString Operations.
2160//===----------------------------------------------------------------------===//
2161
2162extern "C" {
2163const char *clang_getCString(CXString string) {
2164 return string.Spelling;
2165}
2166
2167void clang_disposeString(CXString string) {
2168 if (string.MustFreeString && string.Spelling)
2169 free((void*)string.Spelling);
2170}
Ted Kremenekc0f3f722010-01-22 22:44:15 +00002171
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002172} // end: extern "C"
Ted Kremenekc0f3f722010-01-22 22:44:15 +00002173
2174//===----------------------------------------------------------------------===//
2175// Misc. utility functions.
2176//===----------------------------------------------------------------------===//
2177
2178extern "C" {
2179
2180const char *clang_getClangVersion() {
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00002181 return getClangFullVersion();
Ted Kremenekc0f3f722010-01-22 22:44:15 +00002182}
2183
2184} // end: extern "C"
2185